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 ExcelJS = require('exceljs');
const cors = require('cors');

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.use(cors()); // Enable CORS for all origins
// app.use(cors({
//   origin: '[ http://192.168.1.6:8081 , http://localhost:8081 ]'
// }));

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('/x', function (request, response) {
  if (request.session.loggedin) {
    // Output username
    // response.send('Welcome back, ' + request.session.username + '!');
    console.log(request.session.username, 'open main page');
    // Render home page with username
    response.render('home', { username: request.session.username });
  } else {
    // response.send('Please login to view this page!');
    response.redirect('/login');
  }
});

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.get('/download', async (req, res) => {
    const filename = req.query.filename || 'default.xlsx'; // Get filename from query parameter
    console.log('got the filename', filename);

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Sheet1');

    // Set column widths
    worksheet.columns = [
        { width: 9 },
        { width: 16 },
        { width: 42 },
        { width: 94 }
    ];

    // Add header row
    const headerRow = worksheet.addRow(['Модель', 'Сер.номер', 'Заявленная неисправность', 'Произведенная работа']);

    // Define border style
    const thinBlackBorder = {
        top: { style: 'thin', color: { argb: 'FF000000' } },
        left: { style: 'thin', color: { argb: 'FF000000' } },
        bottom: { style: 'thin', color: { argb: 'FF000000' } },
        right: { style: 'thin', color: { argb: 'FF000000' } }
    };

    // Style the header row
    headerRow.eachCell({ includeEmpty: true }, (cell, colNumber) => {
        cell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: '92D050' }
        };
        cell.font = {
            name: 'Calibri',
            size: 11,
            color: { argb: '000000' },
            bold: false
        };
        cell.alignment = { vertical: 'middle', horizontal: 'center' };
        cell.border = thinBlackBorder;
    });

    // Style the rest of the cells with border
    worksheet.eachRow({ includeEmpty: true }, (row) => {
        row.eachCell({ includeEmpty: true }, (cell) => {
            if (!cell.border) {  // Apply border only if not already defined
                cell.border = thinBlackBorder;
            }
        });
    });

    // Generate buffer from workbook
    const buffer = await workbook.xlsx.writeBuffer();

    // Set headers and send file
    res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(filename)}.xlsx`);
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.send(buffer);
});

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