<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Zapper Dashboard</title>
    <!-- Подключение Font Awesome для иконок -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha384-7Lfqc6il4HoJmf8XzCC8J5IbnY5RvEe1QbkOj3E3kcwYYnI9lN5WRTcuy1ubOYqb" crossorigin="anonymous" />
    <!-- Подключение Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* Основные стили */

        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f6fa;
            color: #333;
        }

        .dashboard {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        @media(min-width: 768px) {
            .dashboard {
                flex-direction: row;
            }
        }

        /* Адаптивное меню */

        .sidebar {
            width: 100%;
            background-color: #fff;
            padding: 20px;
            box-sizing: border-box;
            position: relative;
            z-index: 1000;
        }

        @media(min-width: 768px) {
            .sidebar {
                width: 240px;
                border-right: 1px solid #eee;
                border-bottom: none;
                flex-shrink: 0;
            }
        }

        .navbar-toggle {
            display: block;
            cursor: pointer;
            font-size: 24px;
            margin-bottom: 20px;
        }

        @media(min-width: 768px) {
            .navbar-toggle {
                display: none;
            }
        }

        .sidebar nav {
            display: none;
        }

        @media(min-width: 768px) {
            .sidebar nav {
                display: block;
            }
        }

        .sidebar nav.open {
            display: block;
        }

        .main-content {
            flex-grow: 1;
            padding: 20px;
            box-sizing: border-box;
        }

        .header {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 20px;
        }

        @media(min-width: 576px) {
            .header {
                flex-direction: row;
                justify-content: space-between;
                align-items: center;
            }
        }

        .search-bar {
            width: 100%;
        }

        @media(min-width: 576px) {
            .search-bar {
                flex-grow: 1;
                margin-right: 20px;
            }
        }

        .currency-selector, .user-profile {
            display: flex;
            align-items: center;
            margin-top: 10px;
        }

        @media(min-width: 576px) {
            .currency-selector, .user-profile {
                margin-top: 0;
            }
        }

        .overview {
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin-bottom: 20px;
        }

        @media(min-width: 576px) {
            .overview {
                flex-direction: row;
                justify-content: space-between;
            }
        }

        .overview-item {
            background-color: #fff;
            border-radius: 8px;
            padding: 15px;
            flex: 1 1 100%;
            box-sizing: border-box;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        @media(min-width: 576px) {
            .overview-item {
                flex: 1 1 calc(33.333% - 15px);
            }
        }

        .chart-container,
        .assets-container,
        .transactions {
            background-color: #fff;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-sizing: border-box;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        /* Исправление для графиков */
        .chart-container {
            position: relative;
            height: 400px; /* Установите желаемую высоту */
            width: 100%;
            margin-bottom: 20px;
        }

        .chart-container canvas {
            display: block;
            max-height: 100%;
            max-width: 100%;
        }

        .assets-list {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }

        .asset-item {
            background-color: #f9f9f9;
            border-radius: 8px;
            padding: 15px;
            flex: 1 1 calc(100% - 15px);
            box-sizing: border-box;
        }

        @media(min-width: 576px) {
            .asset-item {
                flex: 1 1 calc(50% - 15px);
            }
        }

        @media(min-width: 992px) {
            .asset-item {
                flex: 1 1 calc(33.333% - 15px);
            }
        }

        .transaction-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .pagination {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
        }

        .page-link {
            margin: 5px;
        }

        .button {
            margin-top: 10px;
        }

        @media(min-width: 768px) {
            .button {
                margin-top: 0;
            }
        }

        /* Общие стили */

        img {
            max-width: 100%;
            height: auto;
        }

        .sidebar ul {
            list-style-type: none;
            padding: 0;
        }

        .sidebar li {
            padding: 10px 0;
            cursor: pointer;
            display: flex;
            align-items: center;
            transition: background-color 0.3s;
        }

        .sidebar li:hover {
            background-color: #f0f0f0;
        }

        .sidebar li i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }

        .sidebar a {
            text-decoration: none;
            color: inherit;
            display: flex;
            align-items: center;
            width: 100%;
        }

        .logo {
            color: #7c5cfc;
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 30px;
        }

        .search-bar input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .currency-selector img, .user-profile img {
            width: 24px;
            height: 24px;
            margin-right: 5px;
        }

        .overview-item h3 {
            margin: 0 0 10px 0;
            font-size: 14px;
            color: #888;
        }

        .overview-item .value {
            font-size: 24px;
            font-weight: bold;
        }

        .overview-item .change {
            font-size: 14px;
        }

        .change.positive { color: #4caf50; }
        .change.negative { color: #f44336; }

        .chart-header, .assets-header {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
            margin-bottom: 15px;
        }

        @media(min-width: 576px) {
            .chart-header, .assets-header {
                flex-direction: row;
                justify-content: space-between;
                align-items: center;
            }
        }

        .button {
            background-color: #7c5cfc;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
        }

        .asset-item div {
            margin-bottom: 5px;
        }

        .transactions h3 {
            margin-bottom: 15px;
        }

        /* Анимации для Transactions */
        .transaction-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #f9f9f9;
            border-radius: 8px;
            padding: 15px;
            transition: background-color 0.3s, transform 0.3s;
            border: 1px solid #e0e0e0;
            opacity: 0;
            transform: translateY(20px);
            animation: fadeInUp 0.5s forwards;
        }

        /* Обновленные задержки анимации для транзакций */
        .transaction-item:nth-child(1) { animation-delay: 0s; }
        .transaction-item:nth-child(2) { animation-delay: 0.1s; }
        .transaction-item:nth-child(3) { animation-delay: 0.2s; }
        .transaction-item:nth-child(4) { animation-delay: 0.3s; }
        .transaction-item:nth-child(5) { animation-delay: 0.4s; }

        @keyframes fadeInUp {
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .transaction-item:hover {
            background-color: #ececec;
            transform: scale(1.02);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .transaction-details {
            display: flex;
            flex-direction: column;
        }

        .transaction-details .user {
            font-weight: bold;
        }

        .transaction-details .date {
            font-size: 12px;
            color: #888;
        }

        .transaction-amount {
            font-weight: bold;
            color: #7c5cfc;
            font-size: 18px;
        }

        .logout {
            margin-top: auto;
            padding: 10px 0;
            color: #f44336;
            cursor: pointer;
            transition: color 0.3s;
        }

        .logout:hover {
            color: #d32f2f;
        }

        /* Стиль для отображения сообщений об ошибках */
        .error-message {
            color: #f44336;
            font-weight: bold;
        }

    </style>
</head>
<body>
    <div class="dashboard">
        <aside class="sidebar">
            <div class="logo">Zapper</div>
            <!-- Кнопка переключения меню -->
            <div class="navbar-toggle"><i class="fas fa-bars"></i></div>
            <nav>
                <ul>
                    <li><a href="#"><i class="fas fa-home"></i> Dashboard</a></li>
                    <li><a href="#"><i class="fas fa-chart-line"></i> Portfolio Performance</a></li>
                    <li><a href="#"><i class="fas fa-briefcase"></i> Transactions</a></li>
                    <li><a href="#"><i class="fas fa-seedling"></i> Farm</a></li>
                    <li><a href="#"><i class="fas fa-archway"></i> Bridge</a></li>
                    <li><a href="#"><i class="fas fa-history"></i> History</a></li>
                    <li><a href="#"><i class="fas fa-cog"></i> Settings</a></li>
                </ul>
            </nav>
            <div class="logout">Logout</div>
        </aside>
        <main class="main-content">
            <header class="header">
                <div class="search-bar">
                    <input type="text" placeholder="Search token, wallet">
                </div>
                <div class="currency-selector">
                    <img src="us-flag.png" alt="USD"> USD
                </div>
                <div class="user-profile">
                    <img src="user-avatar.png" alt="User">
                </div>
            </header>
            <section class="overview">
                <div class="overview-item">
                    <h3>Net Worth</h3>
                    <div class="value">$1365.67</div>
                    <div class="change positive">+5.24%</div>
                </div>
                <div class="overview-item">
                    <h3>Income</h3>
                    <div class="value">$244.67</div>
                    <div class="change positive">+4.36%</div>
                </div>
                <div class="overview-item">
                    <h3>Expenses</h3>
                    <div class="value">$68.67</div>
                    <div class="change negative">-4.36%</div>
                </div>
            </section>
            <section class="chart-container">
                <div class="chart-header">
                    <h3>Portfolio Performance</h3>
                    <select id="portfolioSelect">
                        <option value="monthly">Monthly</option>
                        <option value="yearly">Yearly</option>
                    </select>
                </div>
                <canvas id="portfolioChart"></canvas>
                <!-- Блок для отображения ошибок -->
                <div id="portfolioError" class="error-message"></div>
            </section>
            <section class="chart-container">
                <div class="chart-header">
                    <h3>Weekly Performance</h3>
                    <select id="weeklySelect">
                        <option value="thisWeek">This Week</option>
                        <option value="lastWeek">Last Week</option>
                    </select>
                </div>
                <canvas id="weeklyChart"></canvas>
                <!-- Блок для отображения ошибок -->
                <div id="weeklyError" class="error-message"></div>
            </section>
            <section class="assets-container">
                <div class="assets-header">
                    <h3>All Assets</h3>
                    <button class="button">View All</button>
                </div>
                <div class="assets-list" id="assetsList"></div>
            </section>
            <section class="transactions">
                <h3>Transactions</h3>
                <div id="transactionsList" class="transaction-list"></div>
                <div id="transactionsError" class="error-message"></div>
                <div id="pagination" class="pagination"></div>
            </section>
        </main>
    </div>

    <script>
        // Глобальное логирование ошибок
        window.onerror = function(message, source, lineno, colno, error) {
            console.error(`Error: ${message} at ${source}:${lineno}:${colno}`);
            logError('Global', error || { message, source, lineno, colno });
        };

        window.addEventListener('unhandledrejection', function(event) {
            console.error('Unhandled promise rejection:', event.reason);
            logError('UnhandledPromise', event.reason);
        });

        // Функция логирования ошибок
        function logError(functionName, error) {
            console.error(`Error in ${functionName}:`, error);

            // Вы можете сохранить ошибки в локальном хранилище или отправить их на сервер

            // Пример сохранения в локальном хранилище
            let errorLog = JSON.parse(localStorage.getItem('errorLog')) || [];
            errorLog.push({
                functionName: functionName,
                message: error.message || error.toString(),
                stack: error.stack || null,
                time: new Date().toISOString()
            });
            localStorage.setItem('errorLog', JSON.stringify(errorLog));
        }

        // Функция для отображения сообщений об ошибках пользователю
        function displayError(elementId, message) {
            const errorElement = document.getElementById(elementId);
            if (errorElement) {
                errorElement.textContent = message;
            }
        }

        // Добавление функционала для адаптивного меню
        const navbarToggle = document.querySelector('.navbar-toggle');
        const nav = document.querySelector('.sidebar nav');

        navbarToggle.addEventListener('click', () => {
            nav.classList.toggle('open');
        });

        // Функция инициализации графика
        function createChart(ctx, chartType, data, options) {
            return new Chart(ctx, {
                type: chartType,
                data: data,
                options: options
            });
        }

        // Функция загрузки данных для Portfolio Performance
        async function loadPortfolioData(timeframe = 'monthly') {
            try {
                const response = await fetch(`getPortfolioData.php?timeframe=${timeframe}`);
                if (!response.ok) throw new Error(`Network error: ${response.status}`);

                const data = await response.json();

                if (!data || !Array.isArray(data)) {
                    throw new Error('Invalid data format from server');
                }

                const labels = data.map(item => item.period);
                const values = data.map(item => item.value);

                if (window.portfolioChartInstance) {
                    // Обновление данных графика
                    portfolioChartInstance.data.labels = labels;
                    portfolioChartInstance.data.datasets[0].data = values;
                    portfolioChartInstance.update();
                } else {
                    const ctx = document.getElementById('portfolioChart').getContext('2d');
                    window.portfolioChartInstance = createChart(ctx, 'line', {
                        labels: labels,
                        datasets: [{
                            label: 'Portfolio Value',
                            data: values,
                            backgroundColor: 'rgba(124, 92, 252, 0.2)',
                            borderColor: '#7c5cfc',
                            borderWidth: 1,
                            fill: true,
                            tension: 0.4
                        }]
                    }, {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: false,
                                ticks: {
                                    callback: function(value) {
                                        return '$' + value;
                                    }
                                }
                            }
                        }
                    });
                }
            } catch (error) {
                console.error('Error loading portfolio data:', error);
                logError('loadPortfolioData', error);
                displayError('portfolioError', 'Ошибка загрузки данных для графика Portfolio Performance.');
            }
        }

        // Обработчик события изменения селектора временного периода для Portfolio Performance
        document.getElementById('portfolioSelect').addEventListener('change', (e) => {
            loadPortfolioData(e.target.value);
        });

        // Функция загрузки данных для Weekly Performance
        async function loadWeeklyData(timeframe = 'thisWeek') {
            try {
                const response = await fetch(`getWeeklyData.php?timeframe=${timeframe}`);
                if (!response.ok) throw new Error(`Network error: ${response.status}`);

                const data = await response.json();

                if (!data || !Array.isArray(data)) {
                    throw new Error('Invalid data format from server');
                }

                const labels = data.map(item => item.day);
                const values = data.map(item => item.value);

                if (window.weeklyChartInstance) {
                    // Обновление данных графика
                    weeklyChartInstance.data.labels = labels;
                    weeklyChartInstance.data.datasets[0].data = values;
                    weeklyChartInstance.update();
                } else {
                    const ctx = document.getElementById('weeklyChart').getContext('2d');
                    window.weeklyChartInstance = createChart(ctx, 'bar', {
                        labels: labels,
                        datasets: [{
                            label: 'Weekly Value',
                            data: values,
                            backgroundColor: '#4caf50',
                            borderColor: '#4caf50',
                            borderWidth: 1
                        }]
                    }, {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    callback: function(value) {
                                        return '$' + value;
                                    }
                                }
                            }
                        }
                    });
                }
            } catch (error) {
                console.error('Error loading weekly data:', error);
                logError('loadWeeklyData', error);
                displayError('weeklyError', 'Ошибка загрузки данных для графика Weekly Performance.');
            }
        }

        // Обработчик события изменения селектора временного периода для Weekly Performance
        document.getElementById('weeklySelect').addEventListener('change', (e) => {
            loadWeeklyData(e.target.value);
        });

        // Функции для загрузки Assets и Transactions остаются аналогичными, с добавлением логирования ошибок

        // Функция для загрузки транзакций
        let currentPage = 1;
        const transactionsPerPage = 5;

        async function loadTransactions(page = 1) {
            try {
                // Пример данных транзакций
                const transactions = {
                    data: [
                        { user: 'Alice', date: '2024-12-23 15:45:10', amount: '$100.00' },
                        { user: 'Bob', date: '2024-12-23 15:45:10', amount: '$200.00' },
                        { user: 'Charlie', date: '2024-12-23 15:45:10', amount: '$150.00' },
                        { user: 'David', date: '2024-12-23 15:45:10', amount: '$300.00' },
                        { user: 'Eve', date: '2024-12-23 15:45:10', amount: '$250.00' }
                    ],
                    totalPages: 1
                };

                const transactionsList = document.getElementById('transactionsList');
                transactionsList.innerHTML = '';

                transactions.data.forEach((transaction, index) => {
                    const div = document.createElement('div');
                    div.className = 'transaction-item';

                    // Установка задержки анимации
                    div.style.animationDelay = (index * 0.1) + 's';

                    div.innerHTML = `
                        <div class="transaction-details">
                            <span class="user">${transaction.user}</span>
                            <span class="date">${transaction.date}</span>
                        </div>
                        <div class="transaction-amount">${transaction.amount}</div>
                    `;
                    transactionsList.appendChild(div);
                });

                setPagination(transactions.totalPages);
            } catch (error) {
                console.error('Error loading transactions:', error);
                logError('loadTransactions', error);
                displayError('transactionsError', 'Ошибка загрузки транзакций.');
            }
        }

        function setPagination(totalPages) {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';

            for (let i = 1; i <= totalPages; i++) {
                const pageLink = document.createElement('button');
                pageLink.className = 'page-link';
                pageLink.innerText = i;
                pageLink.onclick = () => {
                    currentPage = i;
                    loadTransactions(currentPage);
                };
                pagination.appendChild(pageLink);
            }
        }

        // Инициализация данных при загрузке страницы
        function init() {
            loadPortfolioData();
            loadWeeklyData();
            loadTransactions(currentPage);
            // Инициализируйте другие данные, если необходимо
        }

        window.onload = init;

    </script>
</body>
</html>
<?php
$servername = "fdb1030.awardspace.net";
$port = 3306;
$username = "4252301_714514419";
$password = "7gkczqm8PR6H"; // Замените на ваш пароль
$dbname = "4252301_714514419";

// Создание соединения
$conn = new mysqli($servername, $username, $password, $dbname, $port);

// Проверка соединения
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT month, value FROM portfolio";
$result = $conn->query($sql);

$data = [];
if ($result->num_rows > 0) {
    // Вывод данных каждой строки
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

$conn->close();

header('Content-Type: application/json');
echo json_encode($data);
?>
<?php
header('Content-Type: application/json');

// Database connection details
$servername = "fdb1030.awardspace.net";
$username = "4252301_714514419";
$password = "7gkczqm8PR6H";
$dbname = "4252301_714514419";
$port = 3306;

$conn = new mysqli($servername, $username, $password, $dbname, $port);

if ($conn->connect_error) {
    die(json_encode(['error' => "Connection failed: " . $conn->connect_error]));
}

$sql = "SELECT DATE_FORMAT(day, '%Y-%m-%d') as day, value FROM performance ORDER BY day ASC";
$result = $conn->query($sql);

if ($result === false) {
    die(json_encode(['error' => "Query failed: " . $conn->error]));
}

$data = array();

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
} 

$conn->close();

echo json_encode($data);
?>
<?php
// getTransactions.php

$servername = "fdb1030.awardspace.net";
$username = "4252301_714514419";
$password = "7gkczqm8PR6H";
$dbname = "4252301_714514419";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 5;

// Determine the start position for the query
$start = ($page - 1) * $limit;

$sql = "SELECT user, amount, date FROM transactions LIMIT $start, $limit";
$result = $conn->query($sql);

$data = array();
$total = $conn->query("SELECT COUNT(*) AS count FROM transactions")->fetch_assoc();
$totalPages = ceil($total['count'] / $limit);

// Fetching transactions data
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

// Prepare response
$response = [
    'data' => $data,
    'totalPages' => $totalPages
];

$conn->close();
echo json_encode($response);
?>

Напиши адаптивный дизайн сайта