const express = require('express');
const fs = require('fs');
const path = require('path');
const mysql = require("mysql2/promise");
const config = require("./config/db.config.js");
const session = require('express-session');
const bcrypt = require('bcrypt');
const signupRouter = require('./signup'); // Adjust path as necessary


const PORT = process.env.PORT || 8080; // Default port is 5000

const log = {
  yellow: '\x1b[33m%s\x1b[0m', //yellow
  cyan: '\x1b[36m%s\x1b[0m',//cyan
  red: '\x1b[31m%s\x1b[0m', //red
  green: '\x1b[32m%s\x1b[0m', //green
  black: '\x1b[30m%s\x1b[0m', //black
  blue: '\x1b[34m%s\x1b[0m', //blue
  gray: '\x1b[90m%s\x1b[0m'  //gray
}


// Create a connection pool
const pool = mysql.createPool({
  host: config.host,
  user: config.user,
  password: config.password,
  database: config.database,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});





const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(session({
  secret: config.secret,
  resave: true,
  saveUninitialized: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));

// Use the signup router
app.use(signupRouter);
 

app.get('/login', function (request, response) {
  /// Render login template with any message from query parameters
  console.log('Message:', request.query.message); // Log the message
  response.render('login', { 
    message: request.query.message || '' , 
    enableSignup: config.enableSignup
  });
});


app.post('/auth', async function (request, response) {
  // Capture the input fields
  const { login, password } = request.body;

  // Ensure the input fields exist and are not empty
  if (login && password) {
    try {
      // Get a connection from the pool
      const connection = await pool.getConnection();
      // const [rows] = await connection.execute(
      //   'SELECT * FROM accounts WHERE (username = ? OR email = ?) AND password = ?',
      //   [login, login]
      // );

      const [rows] = await connection.execute(
        'SELECT * FROM accounts WHERE username = ? OR email = ?',
        [login, login]
      );
      
      // Release the connection back to the pool
      connection.release();
 
      // If the account exists
      if (rows.length > 0) {


        const user = rows[0];
        // console.log(user);
        
         // Compare provided password with stored hashed password
         const match = await bcrypt.compare(password, user.password);

         if (match) {
          request.session.loggedin = true;
          request.session.username = user.username;
          request.session.avatar = user.avatar;

          response.redirect('/');
        } else {
          response.redirect('/login?message=not match Username and/or Password!');
        }
      } else {
        response.redirect('/login?message=Incorrect Username and/or Password!');
      }
    } catch (error) {
      console.error('Database query error:', error);
      response.status(500).send('An error occurred while processing your request.');
    }
  } else {
    response.redirect('/login?message=Please enter Username and Password!');
  }
});

// http://localhost:3000/home
app.get('/', function (request, response) {
  // If the user is loggedin
  if (request.session.loggedin) {
    let avatarSrc = '';
    if (request.session.avatar) {
      // Convert BLOB to Base64 if it exists
      const avatarBase64 = Buffer.from(request.session.avatar).toString('base64');
      avatarSrc = `data:image/jpeg;base64,${avatarBase64}`; // Adjust MIME type as necessary
    }
    // Render home page with username
    response.render('home', {
      username: request.session.username,
      avatar: avatarSrc
    });

  } else {
    // response.send('Please login to view this page!');
    response.redirect('/login');
  }
  response.end();
});


// http://localhost:8080/logout
app.get('/logout', function (request, response) {
  request.session.destroy((err) => {
    if (err) {
      return response.status(500).send('Failed to logout');
    }
    response.redirect('/');
  });
});

// Serve the signup form
app.get('/signup', function (request, response) {

// Check if signup is enabled
if (!config.enableSignup) {
  return response.status(403).send(`
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Signup Disabled</title>
          <style>
              body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
              h1 { color: red; }
              button { padding: 10px 20px; font-size: 16px; }
          </style>
      </head>
      <body>
          <h1>Signup is currently disabled.</h1>
          <p>Please contact the adminstrator for assistance.</p>
          <button onclick="window.location.href='/'">Back to < POS Diagnostic Assist > </button>
      </body>
      </html>
  `);
}

  response.render('signup', { message: request.query.message || '' });
});


app.listen(PORT, () => {
  console.info(`Listening on http://0.0.0.0:${PORT}/`);
});