const express = require("express");
const path = require("path");
const session = require("express-session");
const bcrypt = require("bcrypt");
const pool = require("./config/database"); 
require("dotenv").config();

const app = express(); // ประกาศ app ที่นี่

const MySQLStore = require('express-mysql-session')(session);
const sessionStore = new MySQLStore({}, pool);

// Middleware isLoggedIn
const isLoggedIn = (req, res, next) => {
    if (req.session.user) {
        next();
    } else {
        res.redirect('/login');
    }
};
// Session Configuration
app.use(session({
    secret: process.env.SESSION_SECRET || "mysecret",
    resave: false,
    saveUninitialized: false,
    store: sessionStore, // ใช้ MySQL Store
    cookie: {
        maxAge: 24 * 60 * 60 * 1000, // 24 hours
        secure: false, // true ถ้าใช้ HTTPS
        httpOnly: true,
    },
}));

// Middleware
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Middleware เช็ค Session
app.use((req, res, next) => {
    console.log("Session Middleware Checked");
    next();
});

// View Engine
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

// Routes
const orderRoutes = require("./shop-routes/order");
const cartRoutes = require("./shop-routes/cart");
const indexRoutes = require("./shop-routes/index");

app.use((req, res, next) => {
    res.locals.session = req.session;
    next();
});

app.use("/", indexRoutes);
app.use("/cart", cartRoutes);
app.use("/order", orderRoutes);

// Route สำหรับ Checkout
app.get('/order/checkout', isLoggedIn, (req, res) => {
    console.log("Session:", req.session); // ตรวจสอบ Session
    res.render('checkout'); // แสดงหน้า Checkout
});

app.get('/register', (req, res) => {
    res.render('register');  // ตรวจสอบว่า 'views/login.ejs' มีอยู่จริง
});

// Register Route (POST)
app.post("/register", async (req, res) => {
    try {
        const { email, password, name } = req.body;
        if (!email || !password || !name) {
            return res.status(400).json({ message: "All fields are required." });
        }

        const hashedPassword = await bcrypt.hash(password, 10);
        const [existingUser] = await pool.execute("SELECT * FROM users WHERE email = ?", [email]);

        if (existingUser.length > 0) {
            return res.status(400).json({ message: "Email is already registered." });
        }

        await pool.execute("INSERT INTO users (email, password, name) VALUES (?, ?, ?)", [email, hashedPassword, name]);
        console.log("User registered successfully.");
        res.status(201).json({ success: true, message: "Registration successful." });
    } catch (error) {
        console.error("Registration error:", error);
        res.status(500).json({ message: "Registration failed." });
    }
});

app.get('/login', (req, res) => {
    res.render('login');  // ตรวจสอบว่า 'views/login.ejs' มีอยู่จริง
});

// Login Route (POST)
app.post("/login", async (req, res) => {
    try {
        const { email, password } = req.body;
        if (!email || !password) {
            return res.status(400).json({ message: "All fields are required." });
        }

        const [users] = await pool.execute("SELECT * FROM users WHERE email = ?", [email]);
        if (users.length === 0) {
            return res.status(400).json({ message: "Invalid email or password." });
        }

        const user = users[0];
        const passwordMatch = await bcrypt.compare(password, user.password);
        if (!passwordMatch) {
            return res.status(400).json({ message: "Invalid email or password." });
        }

        req.session.user = { id: user.id, email: user.email };
        console.log("Session after login:", req.session);

        // Redirect ไปยังหน้า Checkout
        return res.redirect('/order/checkout');

    } catch (error) {
        console.error("Login error:", error);
        res.status(500).json({ message: "Login failed." });
    }
});

// Logout Route
app.get("/logout", (req, res) => {
    req.session.destroy((err) => {
        if (err) {
            console.error("Logout error:", err);
            return res.status(500).json({ message: "Logout failed." });
        }
        res.redirect("/login");
    });
});
app.post('/logout', (req, res) => {
    req.session.destroy(err => {
        if (err) {
            return res.status(500).json({ message: "Logout failed" });
        }
        res.clearCookie('connect.sid'); // ล้าง session cookie
        res.status(200).json({ message: "Logged out successfully" });
    });
});
app.get("/search", async (req, res) => {
    const searchQuery = req.query.query;
    try {
        const [results] = await pool.execute(
            "SELECT * FROM products WHERE name LIKE ? OR description LIKE ?",
            [`%${searchQuery}%`, `%${searchQuery}%`]
        );
        res.render("index", { products: results });
    } catch (err) {
        console.error(err);
        res.status(500).send("Error retrieving search results");
    }
});

// Error handler
app.use((err, req, res, next) => {
    console.error("Error:", err.stack);
    res.status(500).json({ message: "Something went wrong." });
});

// Start Server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));