const Order = require('../models/Order');

// Create a new order
exports.createOrder = async (req, res) => {
  try {

    console.log("order is",req.body)

    const newOrder = new Order({
      ...req.body, // Spread the properties from req.body
      closingDate: new Date() // Add closingDate to the object
    });
    
    const savedOrder = await newOrder.save();
    res.status(201).json(savedOrder);
  } catch (error) {
    console.log(error.message)
    res.status(400).json({ error: error.message });
  }
};

// Get all orders
exports.getAllOrders = async (req, res) => {
  try {
    const {companyId, branchId ,start,end} = req.query;
//console.log(req.query)
const startDate = start
  ? new Date(new Date(start).setUTCHours(0, 0, 0, 0))
  : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).setUTCHours(0, 0, 0, 0);// 30 days back by default

    
  




  const endDate = end
    ? new Date(end).setUTCHours(23, 59, 59, 999) // Set end date to the end of the day
    : new Date().setUTCHours(23, 59, 59, 999); // Default to today at 23:59:59
  


// Build the query object
const query = {
 // status: false,
  createdAt: { $gte: new Date(startDate), $lte: new Date(endDate) },
};


if (companyId) query.companyId = companyId; // Filter by companyId if provided
if (branchId) query.branchId = branchId;   // Filter by branchId if provided

    const orders = await Order.find(query).populate('branchId');
    res.status(200).json(orders);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};



// Get a specific order by ID
exports.getOrderById = async (req, res) => {
  try {
    const order = await Order.findById(req.params.id).populate('companyId').populate('branchId');
   
   

    if (!order) return res.status(404).json({ message: 'Order not found' });
    res.status(200).json(order);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// Update an order by ID
exports.updateOrderById = async (req, res) => {
  try {
    // Extract the order ID from params
    const { id } = req.params;
    const closingDate = new Date().toISOString(); // Returns ISO 8601 UTC string

    // Destructure fields from the request body
    const { itemName, customerName, advancePayment, remainingPayment, initialDate,status } = req.body;

    // Fetch the existing order by ID
    const existingOrder = await Order.findById(id);
    if (!existingOrder) {
      return res.status(404).json({ message: 'Order not found' });
    }

    // Extract and compare dates (only date portion, ignoring time)
    const existingDate = new Date(existingOrder.initialDate).toISOString().split('T')[0];
    const todayDate = new Date().toISOString().split('T')[0];

    // Check if the initial order date matches today's date
    if (existingDate !== todayDate) {
      // Partial update: Allow itemName, customerName, and remainingPayment changes
      await Order.findByIdAndUpdate(
        id,
        { remainingPayment, closingDate,status },
        { new: true }
      );
      return res.status(200).json({
        message: 'Order updated, but advance payment and initial order date cannot be changed.',
      });
    }

    // Full update: Allow all fields to be updated
    const updatedOrder = await Order.findByIdAndUpdate(
      id,
      { 
        itemName, 
        customerName, 
        advancePayment, 
        remainingPayment, 
        closingDate,status
      },
      { new: true }
    );
    
    // Return the updated order
    return res.status(200).json({
      message: 'Order updated successfully.',
      updatedOrder,
    });
  } catch (error) {
    // Handle errors and send a response
    return res.status(400).json({ error: error.message });
  }
};


// Delete an order by ID
exports.deleteOrderById = async (req, res) => {
  try {
    const deletedOrder = await Order.findByIdAndDelete(req.params.id);
    if (!deletedOrder) return res.status(404).json({ message: 'Order not found' });
    res.status(200).json({ message: 'Order deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};
