// Import necessary modules
const mongoose = require('mongoose');
const Settings = require('../models/Setting'); // Adjust path as needed
const path = require('path');
const fs = require('fs');

// Create or Update Settings
exports.createOrUpdateSettings = async (req, res) => {
  const { 
    companyId, 
    branchId, 
    defaultStartDate,
    startUpStockValue,
    defaultSmsUserId,
    defaultTimeOut,
    kitchenPrinterIP,
    kitchenPrinterBridgeProtocol,
    kitchenPrinterBridgeIP,
    kitchenPrinterBridgePort,
    companyName
  } = req.body;

console.log(req.body)
 
  try {
    // Convert companyId and branchId to ObjectId
    const companyObjectId = new mongoose.Types.ObjectId(companyId);
    const branchObjectId = new mongoose.Types.ObjectId(branchId);

    // Check if a settings record already exists for the given companyId and branchId
    let settings = await Settings.findOne({ companyId: companyObjectId , branchId: branchObjectId});

    if (settings) {
      // Update the existing settings
      if (defaultStartDate !== undefined) settings.defaultStartDate = defaultStartDate;
      if (startUpStockValue !== undefined) settings.startUpStockValue = Number(startUpStockValue);
      if (defaultSmsUserId !== undefined) settings.defaultSmsUserId = defaultSmsUserId;
      if (defaultTimeOut !== undefined) settings.defaultTimeOut = defaultTimeOut;
      if (companyName !== undefined) settings.companyName = companyName;
      if (req.body.companyLogo !== undefined) settings.companyLogo = req.body.companyLogo;
      
      // Update printer settings if provided
      if (kitchenPrinterIP !== undefined) settings.kitchenPrinterIP = kitchenPrinterIP;
      if (kitchenPrinterBridgeProtocol !== undefined) settings.kitchenPrinterBridgeProtocol = kitchenPrinterBridgeProtocol;
      if (kitchenPrinterBridgeIP !== undefined) settings.kitchenPrinterBridgeIP = kitchenPrinterBridgeIP;
      if (kitchenPrinterBridgePort !== undefined) settings.kitchenPrinterBridgePort = kitchenPrinterBridgePort;
      
      const updatedSettings = await settings.save();
      return res.status(200).json(updatedSettings);
    } else {
      // Create a new settings record
      const newSettings = new Settings({
        companyId: companyObjectId,
        branchId: branchObjectId,
        defaultSmsUserId,
        defaultStartDate,
        defaultTimeOut,
        startUpStockValue: Number(startUpStockValue),
        companyName: companyName || 'Zad',
        companyLogo: req.body.companyLogo || '/uploads/cyber.jpeg',
        kitchenPrinterIP: kitchenPrinterIP || '192.168.20.100',
        kitchenPrinterBridgeProtocol: kitchenPrinterBridgeProtocol || 'http',
        kitchenPrinterBridgeIP: kitchenPrinterBridgeIP || 'localhost',
        kitchenPrinterBridgePort: kitchenPrinterBridgePort || '3000'
      });
      const savedSettings = await newSettings.save();
      return res.status(201).json(savedSettings);
    }
  } catch (error) {
    console.error('Error creating or updating settings:', error.message);
    return res.status(500).json({ message: 'Server error while creating or updating settings.' });
  }
};

  
  // Get Settings
exports.getSettings = async (req, res) => {
    const { companyId, branchId } = req.query;
  
    console.log(req.query);
    try {
      // Convert companyId and branchId to ObjectId
      const companyObjectId = new mongoose.Types.ObjectId(companyId);
      const branchObjectId = new mongoose.Types.ObjectId(branchId);
      
      // Fetch settings based on companyId and branchId
      const settings = await Settings.findOne({ companyId: companyObjectId, branchId: branchObjectId });

     console.log(settings);
      if (!settings) {
        return res.status(404).json({ message: 'Settings not found for the provided company and branch.' });
      }
      return res.status(200).json(settings);
    } catch (error) {
      console.error('Error fetching settings:', error.message);
      return res.status(500).json({ message: 'Server error while fetching settings.' });
    }
  };

  // Delete Settings
exports.deleteSettings = async (req, res) => {
    const { companyId, branchId } = req.query;
  
    try {
      // Delete settings based on companyId and branchId
      const deletedSettings = await Settings.findOneAndDelete({ companyId, branchId });
      if (!deletedSettings) {
        return res.status(404).json({ message: 'Settings not found for the provided company and branch.' });
      }
      return res.status(200).json({ message: 'Settings deleted successfully.' });
    } catch (error) {
      console.error('Error deleting settings:', error.message);
      return res.status(500).json({ message: 'Server error while deleting settings.' });
    }
  };

  // Upload Company Logo
exports.uploadLogo = async (req, res) => {
  const { companyId, branchId } = req.body;

  if (!req.file) {
    return res.status(400).json({ message: 'No file uploaded.' });
  }

  if (!companyId || !branchId) {
    // Delete uploaded file if company/branch ID is missing
    if (req.file.path) {
      fs.unlinkSync(req.file.path);
    }
    return res.status(400).json({ message: 'Company ID and Branch ID are required.' });
  }

  try {
    const companyObjectId = new mongoose.Types.ObjectId(companyId);
    const branchObjectId = new mongoose.Types.ObjectId(branchId);

    // Get the file path relative to the uploads directory
    const logoPath = `/uploads/${req.file.filename}`;

    // Find existing settings
    let settings = await Settings.findOne({ companyId: companyObjectId, branchId: branchObjectId });

    if (settings) {
      // Delete old logo if it exists and is not the default
      if (settings.companyLogo && settings.companyLogo !== '/uploads/cyber.jpeg') {
        const oldLogoPath = path.join(__dirname, '..', settings.companyLogo);
        if (fs.existsSync(oldLogoPath)) {
          fs.unlinkSync(oldLogoPath);
        }
      }
      // Update with new logo
      settings.companyLogo = logoPath;
      await settings.save();
    } else {
      // Create new settings with logo
      settings = new Settings({
        companyId: companyObjectId,
        branchId: branchObjectId,
        companyLogo: logoPath
      });
      await settings.save();
    }

    return res.status(200).json({ 
      message: 'Logo uploaded successfully.',
      logoPath: logoPath 
    });
  } catch (error) {
    // Delete uploaded file on error
    if (req.file.path) {
      fs.unlinkSync(req.file.path);
    }
    console.error('Error uploading logo:', error.message);
    return res.status(500).json({ message: 'Server error while uploading logo.' });
  }
};
  