const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const { updateConfig } = require('./index');

// Create Express app
const app = express();
const PORT = process.env.PORT || 4444;

// Middleware
app.use(express.static(__dirname)); // Serve static files
app.use('/output', express.static(path.join(__dirname, 'output'))); // Serve files from output directory
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Route to serve the HTML form
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

// Route to serve the thank you page
app.get('/thank-you.html', (req, res) => {
  res.sendFile(path.join(__dirname, 'thank-you.html'));
});

// Route to download the generated Excel file
app.get('/download-excel', (req, res) => {
  try {
    // Read the latest config to get store name and other details
    const configPath = path.join(__dirname, 'config.json');
    const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    const storeName = config.user_data?.store_name || 'Your Store';
    
    // Find the most recent Excel file in the output directory
    const outputDir = path.join(__dirname, 'output');
    const files = fs.readdirSync(outputDir)
      .filter(file => file.endsWith('.xlsx') && file.includes(storeName))
      .map(file => ({
        name: file,
        time: fs.statSync(path.join(outputDir, file)).mtime.getTime()
      }))
      .sort((a, b) => b.time - a.time); // Sort by modified time, newest first
    
    if (files.length > 0) {
      const latestFile = files[0].name;
      const filePath = path.join(outputDir, latestFile);
      
      // Set headers for file download
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename="${latestFile}"`);
      
      // Send the file
      res.sendFile(filePath);
      console.log(`Excel file sent for download: ${filePath}`);
    } else {
      res.status(404).send('No Excel file found');
    }
  } catch (error) {
    console.error('Error downloading Excel file:', error);
    res.status(500).send('Error downloading Excel file');
  }
});

// API endpoint to handle form submissions
app.post('/calculate', async (req, res) => {
  try {
    console.log('Received form submission');
    const formData = req.body;
    console.log('Form data received:', JSON.stringify(formData, null, 2));
    
    // Update config file with form data
    await updateConfig(formData);
    console.log('Config file updated successfully');
    
    // Run Python script to create Excel file synchronously
    const { execSync } = require('child_process');
    try {
      console.log('Executing Python script...');
      const stdout = execSync('source venv/bin/activate && python3 create_excel_xlsxwriter.py', {
        encoding: 'utf8',
        shell: '/bin/bash'
      });
      console.log(`Python script output: ${stdout}`);
      
      // Extract the filename from the Python script output
      const filenameMatch = stdout.match(/Excel file created successfully: .*\/output\/(.*\.xlsx)/);
      const excelFilename = filenameMatch ? filenameMatch[1] : null;
      
      if (excelFilename) {
        // Store the filename in a session variable or pass it to the thank-you page
        console.log(`Excel filename extracted: ${excelFilename}`);
      }
      
      // Send success response after Python script completes
      res.json({
        success: true,
        message: 'Form data saved and Excel file created successfully',
        excelFilename: excelFilename
      });
      console.log('Success response sent');
    } catch (execError) {
      console.error(`Error executing Python script: ${execError.message}`);
      if (execError.stderr) {
        console.error(`stderr: ${execError.stderr}`);
      }
      
      // Send error response for Python script failure
      res.status(500).json({
        success: false,
        message: 'Error creating Excel file',
        error: execError.message
      });
      console.error('Error response sent for Python script failure');
    }
  } catch (error) {
    console.error('Error processing form data:', error);
    console.error('Error stack:', error.stack);
    res.status(500).json({
      success: false,
      message: 'Error processing form data',
      error: error.message
    });
    console.error('Error response sent');
  }
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
}); 