<?php
header('Content-Type: application/json');

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

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

// Check connection
if ($conn->connect_error) {
    die(json_encode(['status' => 'error', 'message' => 'Connection failed: ' . $conn->connect_error]));
}

// Получаем данные из POST-запроса
$data = json_decode(file_get_contents('php://input'), true);
$user = $data['user'];
$amount = $data['amount'];
$date = $data['date'];

// Вставляем транзакцию
$stmt = $conn->prepare("INSERT INTO financial_transactions (user, amount, date) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $user, $amount, $date);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Transaction inserted successfully']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Error inserting transaction: ' . $stmt->error]);
}

$stmt->close();
$conn->close();
?>
<?php
header('Content-Type: application/json');

// Включаем логирование ошибок
ini_set('log_errors', 1);
ini_set('error_log', 'delete_transaction_errors.log');

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

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

// Проверяем соединение
if ($conn->connect_error) {
    error_log("Connection failed: " . $conn->connect_error); // Логируем ошибку
    die(json_encode(['status' => 'error', 'message' => 'Connection failed: ' . $conn->connect_error]));
}

// Получаем ID из запроса
$id = $_GET['id'];

// Подготавливаем запрос на удаление
$stmt = $conn->prepare("DELETE FROM financial_transactions WHERE id = ?");
if (!$stmt) {
    error_log("Prepare failed: " . $conn->error); // Логируем ошибку
    die(json_encode(['status' => 'error', 'message' => 'Prepare failed: ' . $conn->error]));
}

$stmt->bind_param("i", $id);

// Выполняем запрос
if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Transaction deleted successfully']);
} else {
    error_log("Execute failed: " . $stmt->error); // Логируем ошибку
    echo json_encode(['status' => 'error', 'message' => 'Error deleting transaction: ' . $stmt->error]);
}

$stmt->close();
$conn->close();
?>
<?php
header('Content-Type: application/json');

// Включаем логирование ошибок
ini_set('log_errors', 1);
ini_set('error_log', 'fetch_transactions_errors.log');

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

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

// Проверяем соединение
if ($conn->connect_error) {
    error_log("Connection failed: " . $conn->connect_error); // Логируем ошибку
    die(json_encode(['status' => 'error', 'message' => 'Connection failed: ' . $conn->connect_error]));
}

// Выполняем запрос
$sql = "SELECT id, user, amount, date FROM financial_transactions";
$result = $conn->query($sql);

if (!$result) {
    error_log("Query failed: " . $conn->error); // Логируем ошибку
    die(json_encode(['status' => 'error', 'message' => 'Query failed: ' . $conn->error]));
}

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

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

// Включаем логирование ошибок
ini_set('log_errors', 1);
ini_set('error_log', 'update_transaction_errors.log');

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

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

// Проверяем соединение
if ($conn->connect_error) {
    error_log("Connection failed: " . $conn->connect_error); // Логируем ошибку
    die(json_encode(['status' => 'error', 'message' => 'Connection failed: ' . $conn->connect_error]));
}

// Получаем ID из запроса
$id = $_GET['id'];

// Получаем данные из тела запроса
$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
    error_log("Invalid JSON data received"); // Логируем ошибку
    die(json_encode(['status' => 'error', 'message' => 'Invalid JSON data received']));
}

$user = $data['user'];
$amount = $data['amount'];
$date = $data['date'];

// Подготавливаем запрос на обновление
$stmt = $conn->prepare("UPDATE financial_transactions SET user = ?, amount = ?, date = ? WHERE id = ?");
if (!$stmt) {
    error_log("Prepare failed: " . $conn->error); // Логируем ошибку
    die(json_encode(['status' => 'error', 'message' => 'Prepare failed: ' . $conn->error]));
}

$stmt->bind_param("sssi", $user, $amount, $date, $id);

// Выполняем запрос
if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Transaction updated successfully']);
} else {
    error_log("Execute failed: " . $stmt->error); // Логируем ошибку
    echo json_encode(['status' => 'error', 'message' => 'Error updating transaction: ' . $stmt->error]);
}

$stmt->close();
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transaction Dashboard</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            background-color: #f9f9f9;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .header button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: transform 0.2s ease, background-color 0.3s;
        }
        .header button:hover {
            transform: scale(1.05); /* Увеличиваем кнопку на 5% */
            background-color: #0056b3;
        }
        .transactions {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .transactions ul {
            list-style: none;
            padding: 0;
        }
        .transactions li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #ddd;
            transition: transform 0.2s ease, background-color 0.3s;
        }
        .transactions li:hover {
            transform: translateX(5px); /* Сдвигаем элемент вправо на 5px */
            background-color: #f1f1f1;
        }
        .transactions li button {
            margin-left: 10px;
            padding: 5px 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .transactions li button.edit {
            background-color: #28a745;
            color: white;
        }
        .transactions li button.delete {
            background-color: #dc3545;
            color: white;
        }
        .transactions li button:hover {
            opacity: 0.8;
        }
        .chart-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .filter-container {
            margin-bottom: 20px;
        }
        .filter-container label {
            margin-right: 10px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        .pagination button {
            margin: 0 5px;
            padding: 5px 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            background-color: #007bff;
            color: white;
        }
        .pagination button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        #overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }
        #transactionModal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            z-index: 1001;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <div id="app">
        <div class="container">
            <!-- Header -->
            <div class="header">
                <h1>Transaction Dashboard</h1>
                <button @click="openModal">Add Transaction</button>
            </div>

            <!-- Transactions List -->
            <div class="transactions">
                <h2>Transactions</h2>
                <ul>
                    <li v-for="transaction in paginatedTransactions" :key="transaction.id">
                        <span>{{ transaction.user }} - {{ transaction.amount }} - {{ transaction.date }}</span>
                        <div>
                            <button class="edit" @click="editTransaction(transaction)">Edit</button>
                            <button class="delete" @click="deleteTransaction(transaction.id)">Delete</button>
                        </div>
                    </li>
                </ul>
                <div class="pagination">
                    <button @click="prevPage" :disabled="currentPage === 1">Previous</button>
                    <span>Page {{ currentPage }} of {{ totalPages }}</span>
                    <button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
                </div>
            </div>

            <!-- Chart Section -->
            <div class="chart-container">
                <h2>Transaction Chart</h2>
                <div class="filter-container">
                    <label for="startDate">Start Date:</label>
                    <input type="date" v-model="startDate">
                    <label for="endDate">End Date:</label>
                    <input type="date" v-model="endDate">
                    <button @click="applyDateFilter">Apply Filter</button>
                </div>
                <canvas id="transactionChart"></canvas>
            </div>

            <!-- Modal for adding/editing a transaction -->
            <div id="overlay" v-if="isModalOpen" @click="closeModal"></div>
            <div id="transactionModal" v-if="isModalOpen">
                <h3>{{ modalTitle }}</h3>
                <form @submit.prevent="submitForm">
                    <input type="hidden" v-model="currentTransactionId">
                    <div class="form-group">
                        <label for="user">User:</label>
                        <input type="text" v-model="form.user" required>
                    </div>
                    <div class="form-group">
                        <label for="amount">Amount:</label>
                        <input type="text" v-model="form.amount" required>
                    </div>
                    <div class="form-group">
                        <label for="date">Date and Time:</label>
                        <input type="datetime-local" v-model="form.date" required>
                    </div>
                    <button type="submit">Submit</button>
                    <button type="button" @click="closeModal">Cancel</button>
                </form>
            </div>
        </div>
    </div>

    <script>
        new Vue({
            el: '#app',
            data: {
                transactions: [],
                filteredTransactions: [],
                currentPage: 1,
                itemsPerPage: 5,
                startDate: '',
                endDate: '',
                isModalOpen: false,
                modalTitle: 'Add New Transaction',
                currentTransactionId: null,
                form: {
                    user: '',
                    amount: '',
                    date: ''
                },
                transactionChart: null
            },
            computed: {
                totalPages() {
                    return Math.ceil(this.filteredTransactions.length / this.itemsPerPage);
                },
                paginatedTransactions() {
                    const start = (this.currentPage - 1) * this.itemsPerPage;
                    const end = start + this.itemsPerPage;
                    return this.filteredTransactions.slice(start, end);
                }
            },
            methods: {
                async loadTransactions() {
                    try {
                        const response = await fetch('fetch_transactions.php');
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.message || 'Failed to load transactions');
                        }
                        this.transactions = await response.json();
                        this.filteredTransactions = this.transactions;
                        this.updateChart();
                    } catch (error) {
                        console.error('Error loading transactions:', error.message);
                        alert('Error loading transactions: ' + error.message);
                    }
                },
                openModal() {
                    this.isModalOpen = true;
                    this.modalTitle = 'Add New Transaction';
                    this.form = { user: '', amount: '', date: '' };
                    this.currentTransactionId = null;
                    document.addEventListener('keydown', this.handleEscape);
                },
                closeModal() {
                    this.isModalOpen = false;
                    document.removeEventListener('keydown', this.handleEscape);
                },
                handleEscape(event) {
                    if (event.key === 'Escape') {
                        this.closeModal();
                    }
                },
                editTransaction(transaction) {
                    this.isModalOpen = true;
                    this.modalTitle = 'Edit Transaction';
                    this.form = { ...transaction };
                    this.currentTransactionId = transaction.id;
                },
                async deleteTransaction(id) {
                    if (!confirm('Are you sure you want to delete this transaction?')) return;
                    try {
                        const response = await fetch(delete_transaction.php?id=${id}, {
                            method: 'DELETE'
                        });
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.message || 'Failed to delete transaction');
                        }
                        this.loadTransactions();
                    } catch (error) {
                        console.error('Error deleting transaction:', error.message);
                        alert('Error deleting transaction: ' + error.message);
                    }
                },
                async submitForm() {
                    const url = this.currentTransactionId ? update_transaction.php?id=${this.currentTransactionId} : 'add_transaction.php';
                    const method = this.currentTransactionId ? 'PUT' : 'POST';
                    try {
                        const response = await fetch(url, {
                            method,
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(this.form)
                        });
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.message || 'Failed to save transaction');
                        }
                        this.loadTransactions();
                        this.closeModal();
                    } catch (error) {
                        console.error('Error saving transaction:', error.message);
                        alert('Error saving transaction: ' + error.message);
                    }
                },
                applyDateFilter() {
                    this.filteredTransactions = this.transactions.filter(transaction => {
                        const transactionDate = new Date(transaction.date);
                        const start = this.startDate ? new Date(this.startDate) : null;
                        const end = this.endDate ? new Date(this.endDate) : null;
                        return (!start || transactionDate >= start) && (!end || transactionDate <= end);
                    });
                    this.currentPage = 1;
                    this.updateChart();
                },
                updateChart() {
                    const ctx = document.getElementById('transactionChart').getContext('2d');
                    if (this.transactionChart) this.transactionChart.destroy();
                    this.transactionChart = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: this.filteredTransactions.map(t => t.date),
                            datasets: [{
                                label: 'Transaction Amount',
                                data: this.filteredTransactions.map(t => parseFloat(t.amount.replace(/[^0-9.-]+/g, ''))),
                                backgroundColor: this.filteredTransactions.map(t => parseFloat(t.amount.replace(/[^0-9.-]+/g, '')) > 50 ? 'rgba(75, 192, 192, 0.2)' : 'rgba(255, 99, 132, 0.2)'),
                                borderColor: this.filteredTransactions.map(t => parseFloat(t.amount.replace(/[^0-9.-]+/g, '')) > 50 ? 'rgba(75, 192, 192, 1)' : 'rgba(255, 99, 132, 1)'),
                                borderWidth: 1
                            }]
                        },
                        options: {
                            scales: { y: { beginAtZero: true } }
                        }
                    });
                },
                nextPage() {
                    if (this.currentPage < this.totalPages) this.currentPage++;
                },
                prevPage() {
                    if (this.currentPage > 1) this.currentPage--;
                }
            },
            mounted() {
                this.loadTransactions();
            }
        });
    </script>
</body>
</html>
Предложи улучшения для сайта