const express = require('express');
const mysql = require('mysql2');
const fs = require('fs');

const PORT = 3001;

// Function to start the Express server (only used if you pass --server)
const startServer = () => {
  const app = express();
  app.use(express.json());
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
  });
};

// MySQL connection configuration
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'sooggoo',
  password: '4Compassion*',
  database: 'evergreenint',
});

// Function that fetches labour cost data and writes it to a JSON file
const fetchAndSaveLabourCostReport = async (fromDate, toDate) => {
	  const actualFromDate = fromDate || '1';      
  const actualToDate   = toDate   || '9999';   
  const query = `
    SELECT manual_tech_timesheet.labourcode,
           SUM(manual_tech_timesheet.cost) AS cost,
           SUM(manual_tech_timesheet.fnpf) AS fnpfcost,
           SUM(manual_tech_timesheet.tpaf) AS tpafcost,
           SUM(manual_tech_timesheet.cost_including_fnpf) AS totalcost,
           SUM(manual_tech_timesheet.th) AS totalhours,
           labourcodes.name
    FROM manual_tech_timesheet
    INNER JOIN labourcodes ON manual_tech_timesheet.labourcode = labourcodes.code
    WHERE manual_tech_timesheet.id BETWEEN ? AND ?
    GROUP BY manual_tech_timesheet.labourcode
  `;

  const params = [actualFromDate, actualToDate,];

  try {
    const [rows] = await connection.promise().query(query, params);

    if (rows.length > 0) {
      const jsonData = JSON.stringify(rows);
      const reportPath = '/home/erp/www/wormalderp/nodejsapp/techniciancost.json';
      fs.writeFileSync(reportPath, jsonData);
      console.log(`Labour cost report saved to ${reportPath}`);
    } else {
      console.log('No labour cost data available for the selected date range.');
    }
  } catch (error) {
    console.error('Error fetching labour cost data:', error);
  } finally {
    connection.end();
  }
};

// Function to run the report and then exit the process
const runLabourCostReportAndExit = async () => {
  // You can get the command line args here, for example:
  const fromDate = process.argv[2];
  const toDate = process.argv[3];

  await fetchAndSaveLabourCostReport(fromDate, toDate);
  process.exit(0);
};

// If the '--server' flag is provided, start the server; otherwise, run the report and exit.
if (process.argv.includes('--server')) {
  startServer();
} else {
  runLabourCostReportAndExit();
}
