// index.js
const express = require('express');
const mysql = require('mysql2');
const app = express();
const port = 3000;
const cors = require('cors');

// 创建 MySQL 数据库连接
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'express_db'
});

// 连接到 MySQL 数据库
db.connect((err) => {
    if (err) {
        console.error('Error connecting to MySQL database:', err);
        return;
    }
    console.log('Connected to MySQL database');
});

// 设置 Express 应用的 JSON 和urlencoded中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());

app.set('view engine', 'ejs');
app.set('views', './public');


app.get('/register-page', (req, res) => {
    res.render('register');
})

// 处理表单提交的路由
app.post('/register', (req, res) => {
    const { username, password, email, gender, hobbies, city, description } = req.body;

    let hobbiesStr = '';
    if (Array.isArray(hobbies)) {
        hobbiesStr = hobbies.join(',');
    } else if (hobbies) {
        hobbiesStr = hobbies;
    }

    // 构建插入数据的 SQL 语句
    const sql = 'INSERT INTO users (username, password, email, gender, hobbies, city, description) VALUES (?, ?, ?, ?, ?, ?, ?)';
    const values = [username, password, email, gender, hobbiesStr, city, description];

    // 执行 SQL 语句
    db.query(sql, values, (err, result) => {
        if (err) {
            console.error('Error inserting data into MySQL database:', err);
            res.status(500).send('Error inserting data into MySQL database');
            return;
        }
        console.log('Data inserted successfully');
        res.send('Registration successful');
    });
});


app.get('/login-page', (req, res) => {
    res.render('login');
});

// 处理登录表单提交
app.post('/login', (req, res) => {
    const { username, password } = req.body;

    // 构建查询用户的 SQL 语句
    const sql = 'SELECT * FROM users WHERE username = ? AND password = ?';
    const values = [username, password];

    // 执行 SQL 语句
    db.query(sql, values, (err, results) => {
        if (err) {
            console.error('Error querying the database:', err);
            return;
        }

        if (results.length > 0) {
            console.log('Login successful');
            res.render('login', { message: '登录成功！' });
        } else {
            console.log('Login failed');
            res.render('login', { message: '用户名或密码错误' });
        }
    });
});



app.get('/update-password-page', (req, res) => {
    res.render('update-password');
})

// 处理更新用户密码的路由
app.post('/update-password', (req, res) => {
    const { username, currentPassword, newPassword } = req.body;

    // 验证当前密码是否正确
    const sqlCheck = 'SELECT * FROM users WHERE username = ? AND password = ?';
    const checkValues = [username, currentPassword];

    db.query(sqlCheck, checkValues, (err, results) => {
        if (err) {
            console.error('Error querying the database:', err);
            res.status(500).send('Error querying the database');
            return;
        }

        if (results.length === 0) {
            console.log('当前密码输入错误');
            res.status(400).send('Current password is incorrect');
            return;
        }

        // 当前密码正确，更新新密码
        const sqlUpdate = 'UPDATE users SET password = ? WHERE username = ?';
        const updateValues = [newPassword, username];

        db.query(sqlUpdate, updateValues, (err, result) => {
            if (err) {
                console.error('Error updating user password:', err);
                res.status(500).send('Error updating user password');
                return;
            }
            console.log('User password updated successfully');
            res.send('User password updated successfully');
        });
    });
});

// 启动服务器
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});