const multer = require('multer');
const path = require('path');
const fs = require('fs');
const mongoose = require('mongoose');
const Order = require('../models/Order');
const Item = require('../models/Item');
const User = require('../models/User');
const Prescription = require('../models/Prescription');
const Store = require('../models/Store');
const asyncHandler = require('../middleware/async');
const ErrorResponse = require('../utils/errorResponse');
const sendEmail = require('../utils/sendEmail');
const { refundPayment, processPayment } = require('../services/paymentService');

// Configure multer for prescription uploads
const uploadsDir = path.join(process.cwd(), 'uploads');
const uploadDir = path.join(uploadsDir, 'prescriptions');

// Ensure upload directories exist
[uploadsDir, uploadDir].forEach(dir => {
  if (!fs.existsSync(dir)) {
    try {
      fs.mkdirSync(dir, { recursive: true, mode: 0o777 });
      console.log(`Created directory: ${dir}`);
    } catch (err) {
      console.error(`Error creating directory ${dir}:`, err);
    }
  }
});

const fileFilter = (req, file, cb) => {
  // Accept images and PDFs
  if (file.mimetype.startsWith('image/') || file.mimetype === 'application/pdf') {
    cb(null, true);
  } else {
    cb(new Error('Only image files (jpg, jpeg, png, gif) and PDFs are allowed!'), false);
  }
};

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const dir = path.join(__dirname, '../uploads/prescriptions');
    // Create directory if it doesn't exist
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    cb(null, dir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname).toLowerCase();
    cb(null, 'rx-' + uniqueSuffix + ext);
  }
});

const upload = multer({ 
  storage: storage,
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB limit
  fileFilter: fileFilter
});

// @desc    Get orders for pharmacist's store
// @route   GET /api/v1/orders/pharmacist/store-orders
// @access  Private/Pharmacist
exports.getPharmacistStoreOrders = asyncHandler(async (req, res, next) => {
  // Get pharmacist's store ID from their profile
  const pharmacist = await User.findById(req.user.id).select('store assignedStores');
  
  // Check if pharmacist has a store assigned
  let storeId = pharmacist?.store;
  
  // If no direct store assignment, check assignedStores array
  if (!storeId && pharmacist?.assignedStores?.length > 0) {
    storeId = pharmacist.assignedStores[0]; // Get the first assigned store
  }
  
  if (!storeId) {
    return next(new ErrorResponse('No store associated with this pharmacist', 400));
  }

  // Build query with all relevant statuses
  const query = {
    store: storeId,
    status: { 
      $in: [
        'PENDING', 
        'PENDING_VERIFICATION', 
        'PROCESSING', 
        'CONFIRMED',
        'APPROVED',
        'SHIPPED',
        'OUT_FOR_DELIVERY',
        'READY_FOR_PICKUP',
        'DELIVERED',
        'COMPLETED',
        'CANCELLED',
        'REJECTED'
      ] 
    }
  };

  // Add status filter if provided in query
  if (req.query.status) {
    if (Array.isArray(req.query.status)) {
      query.status = { $in: req.query.status };
    } else if (req.query.status === 'pending') {
      query.status = { 
        $in: ['PENDING', 'PENDING_VERIFICATION', 'PROCESSING', 'CONFIRMED'] 
      };
    } else if (req.query.status === 'approved') {
      query.status = { 
        $in: ['APPROVED', 'SHIPPED', 'OUT_FOR_DELIVERY', 'READY_FOR_PICKUP'] 
      };
    } else if (req.query.status === 'completed') {
      query.status = { 
        $in: ['DELIVERED', 'COMPLETED'] 
      };
    } else if (req.query.status === 'cancelled') {
      query.status = { 
        $in: ['CANCELLED', 'REJECTED'] 
      };
    } else {
      query.status = req.query.status.toUpperCase();
    }
  }

  // Add search filter if provided
  if (req.query.search) {
    query.$or = [
      { orderNumber: { $regex: req.query.search, $options: 'i' } },
      { 'user.name': { $regex: req.query.search, $options: 'i' } },
      { 'user.email': { $regex: req.query.search, $options: 'i' } },
      { 'prescription.patient_name': { $regex: req.query.search, $options: 'i' } },
      { 'prescription.doctor_name': { $regex: req.query.search, $options: 'i' } }
    ];
  }

  // Build pagination
  const page = parseInt(req.query.page, 10) || 1;
  const limit = parseInt(req.query.limit, 10) || 10;
  const startIndex = (page - 1) * limit;
  const endIndex = page * limit;
  const total = await Order.countDocuments(query);

  // Execute query with pagination
  const orders = await Order.find(query)
    .populate({
      path: 'userId',
      select: 'name email phone',
      match: { deletedAt: { $exists: false } }
    })
    .populate({
      path: 'items.item',
      select: 'name price image brand category unit',
      populate: [
        { 
          path: 'brand', 
          select: 'name',
          match: { deletedAt: { $exists: false } }
        },
        { 
          path: 'category', 
          select: 'name',
          match: { deletedAt: { $exists: false } }
        },
        { 
          path: 'unit', 
          select: 'name shortCode',
          match: { deletedAt: { $exists: false } }
        }
      ]
    })
    .populate({
      path: 'prescription',
      select: 'status patient_name doctor_name patient_age patient_gender diagnosis notes images',
      match: { deletedAt: { $exists: false } }
    })
    .populate({
      path: 'store',
      select: 'name address contactInfo',
      match: { deletedAt: { $exists: false } }
    })
    .sort({ createdAt: -1 })
    .skip(startIndex)
    .limit(limit);

  // Pagination result
  const pagination = {};
  if (endIndex < total) {
    pagination.next = {
      page: page + 1,
      limit
    };
  }

  if (startIndex > 0) {
    pagination.prev = {
      page: page - 1,
      limit
    };
  }

  res.status(200).json({
    success: true,
    count: orders.length,
    data: orders
  });
});

// @desc    Get single order
// @route   GET /api/v1/orders/:id
// @access  Private
exports.getOrder = asyncHandler(async (req, res, next) => {
  const order = await Order.findById(req.params.id)
    .populate('userId', 'name email phone')
    .populate('deliveryInfo.deliveryBoy', 'name phone')
    .populate({
      path: 'items.item',
      select: 'name price image brand category unit weight',
      populate: [
        { path: 'brand', select: 'name' },
        { path: 'category', select: 'name' },
        { path: 'unit', select: 'name shortCode' }
      ]
    })
    .populate('store', 'name address contactInfo')
    .populate('prescription.reviewedBy', 'name email role');

  if (!order) {
    return next(
      new ErrorResponse(`Order not found with id of ${req.params.id}`, 404)
    );
  }

  // Make sure user is order owner or admin
  if (order.user._id.toString() !== req.user.id && req.user.role !== 'admin') {
    return next(
      new ErrorResponse(
        `User ${req.user.id} is not authorized to access this order`,
        401
      )
    );
  }

  res.status(200).json({
    success: true,
    data: order
  });
});

// @desc    Get all orders
// @route   GET /api/v1/orders
// @access  Private/Admin
exports.getAllOrders = asyncHandler(async (req, res, next) => {
  // Copy req.query
  const reqQuery = { ...req.query };

  // Fields to exclude
  const removeFields = ['select', 'sort', 'page', 'limit'];

  // Loop over removeFields and delete them from reqQuery
  removeFields.forEach(param => delete reqQuery[param]);

  // Handle prescription status filter
  if (req.query.prescriptionStatus) {
    if (req.query.prescriptionStatus === 'pending') {
      // Find orders that either have a pending prescription or require prescription verification
      reqQuery.$or = [
        { 'prescription.status': { $in: ['pending', 'in_review'] } },
        { 
          'items.requiresPrescription': true,
          'prescription.status': { $exists: false }
        }
      ];
    } else {
      reqQuery['prescription.status'] = req.query.prescriptionStatus;
    }
    // Remove the prescriptionStatus from the query to avoid conflicts
    delete reqQuery.prescriptionStatus;
  }

  // Create query string
  let queryStr = JSON.stringify(reqQuery);

  // Create operators ($gt, $gte, etc)
  queryStr = queryStr.replace(/\b(gt|gte|lt|lte|in)\b/g, match => `$${match}`);

  // Finding resource
  let query = Order.find(JSON.parse(queryStr));
  
  // Always populate prescription if it exists
  query = query.populate('prescription');

  // Select Fields
  if (req.query.select) {
    const fields = req.query.select.split(',').join(' ');
    query = query.select(fields);
  }

  // Sort
  if (req.query.sort) {
    const sortBy = req.query.sort.split(',').join(' ');
    query = query.sort(sortBy);
  } else {
    query = query.sort('-createdAt');
  }

  // Pagination
  const page = parseInt(req.query.page, 10) || 1;
  const limit = parseInt(req.query.limit, 10) || 25;
  const startIndex = (page - 1) * limit;
  const endIndex = page * limit;
  const total = await Order.countDocuments(JSON.parse(queryStr));

  query = query.skip(startIndex).limit(limit);

  // Populate related data
  query = query.populate([
    { path: 'user', select: 'name email phone' },
    { path: 'items.item', select: 'name price image brand category unit requiresPrescription' },
    { 
      path: 'prescription',
      select: 'status images prescription_date is_verified verification_history',
      populate: {
        path: 'verification_history.changed_by',
        select: 'name email role'
      }
    }
  ]);

  // Executing query
  const orders = await query;
  
  console.log('Found orders with prescriptions:', orders.length);

  // Pagination result
  const pagination = {};

  if (endIndex < total) {
    pagination.next = {
      page: page + 1,
      limit
    };
  }

  if (startIndex > 0) {
    pagination.prev = {
      page: page - 1,
      limit
    };
  }

  res.status(200).json({
    success: true,
    count: orders.length,
    pagination,
    data: orders
  });
});

// @desc    Get prescription history for an order
// @route   GET /api/v1/orders/:id/prescription-history
// @access  Private/Admin/Pharmacist
exports.getPrescriptionHistory = asyncHandler(async (req, res, next) => {
  const { id } = req.params;

  const order = await Order.findById(id)
    .select('prescription prescriptionHistory')
    .populate('prescription.reviewedBy', 'name email role')
    .populate('prescriptionHistory.reviewedBy', 'name email role');
  
  if (!order) {
    return next(new ErrorResponse(`Order not found with id of ${id}`, 404));
  }

  // Check if order has a prescription
  if (!order.prescription) {
    return next(new ErrorResponse('No prescription found for this order', 404));
  }

  // Prepare response data
  const responseData = {
    currentPrescription: order.prescription,
    history: order.prescriptionHistory || []
  };

  res.status(200).json({
    success: true,
    data: responseData
  });
});

// @desc    Update prescription status
// @route   PUT /api/v1/orders/:id/prescription/status
// @access  Private/Admin/Pharmacist
exports.updatePrescriptionStatus = asyncHandler(async (req, res, next) => {
  const { status } = req.body;
  const { id } = req.params;

  // Validate status
  if (!['approved', 'rejected', 'pending'].includes(status)) {
    return next(new ErrorResponse('Invalid status. Must be one of: approved, rejected, pending', 400));
  }

  const order = await Order.findById(id);
  
  if (!order) {
    return next(new ErrorResponse(`Order not found with id of ${id}`, 404));
  }

  // Check if order has a prescription
  if (!order.prescription) {
    return next(new ErrorResponse('No prescription found for this order', 400));
  }

  // Update prescription status
  order.prescription.status = status;
  order.prescription.reviewedBy = req.user.id;
  order.prescription.reviewedAt = Date.now();

  // Update order status based on prescription status
  if (status === 'approved') {
    order.status = 'processing';
  } else if (status === 'rejected') {
    order.status = 'prescription_rejected';
  }

  await order.save({ validateBeforeSave: false });

  // TODO: Send notification to user about prescription status update

  res.status(200).json({
    success: true,
    data: order
  });
});

// @desc    Upload prescription for an order
// @route   POST /api/v1/orders/:id/prescription
// @access  Private
exports.uploadOrderPrescription = asyncHandler(async (req, res, next) => {
  const order = await Order.findById(req.params.id);
  
  if (!order) {
    return next(new ErrorResponse(`Order not found with id of ${req.params.id}`, 404));
  }

  // Make sure user is order owner or admin
  if (order.user.toString() !== req.user.id && req.user.role !== 'admin') {
    return next(
      new ErrorResponse(
        `User ${req.user.id} is not authorized to update this order`,
        401
      )
    );
  }

  // Check if file was uploaded
  if (!req.file) {
    return next(new ErrorResponse('Please upload a file', 400));
  }

  // Update order with prescription details
  order.prescription = {
    fileName: req.file.filename,
    filePath: `/uploads/prescriptions/${req.file.filename}`,
    status: 'pending',
    uploadedAt: Date.now()
  };

  // Update order status if it was waiting for prescription
  if (order.status === 'pending_prescription') {
    order.status = 'processing';
  }

  await order.save({ validateBeforeSave: false });

  res.status(200).json({
    success: true,
    data: order
  });
});

// @desc    Check if any items in the order require a prescription
// @param   {Array} items - Array of order items
// @returns {Object} Object containing requiresPrescription flag and updated items
const checkPrescriptionRequirements = async (items) => {
  try {
    if (!items || !Array.isArray(items) || items.length === 0) {
      console.log('No items in order to check prescription requirements');
      return { requiresPrescription: false, items: [] };
    }

    // First check if any items already have requiresPrescription set
    const hasPrescriptionInItems = items.some(item => item.requiresPrescription === true);
    if (hasPrescriptionInItems) {
      console.log('Found items with requiresPrescription flag already set');
      return {
        requiresPrescription: true,
        items: items.map(item => ({
          ...item,
          requiresPrescription: item.requiresPrescription === true
        }))
      };
    }

    const itemIds = items
      .map(item => item.item || item.id || (item.productDetails && item.productDetails._id))
      .filter(Boolean);
    
    if (itemIds.length === 0) {
      console.log('No valid item IDs found in the order');
      return { 
        requiresPrescription: false, 
        items: items.map(item => ({
          ...item,
          requiresPrescription: false
        }))
      };
    }
    
    // Get all items from the database to check prescription requirements
    const itemDocs = await Item.find({ _id: { $in: itemIds } });
    
    // Create a map of item IDs to their details
    const itemMap = {};
    itemDocs.forEach(item => {
      if (item) {
        itemMap[item._id.toString()] = item;
      }
    });
    
    // Debug logs
    console.log('Checking prescription requirements for items:', JSON.stringify(items, null, 2));
    console.log('Item map from DB:', Object.keys(itemMap));
    
    // Check if any item requires a prescription
    let requiresPrescription = false;
    const updatedItems = items.map(cartItem => {
      // Try different ways to find the item ID
      const itemId = (
        cartItem.item?.toString() || 
        cartItem.id?.toString() || 
        (cartItem.productDetails && cartItem.productDetails._id?.toString()) ||
        (cartItem.productDetails && cartItem.productDetails.id?.toString())
      );
      
      const item = itemId ? itemMap[itemId] : null;
      
      // Check if item exists and has requiresPrescription flag
      const needsPrescription = item ? 
        (item.requiresPrescription === true) : 
        (cartItem.requiresPrescription === true || 
         (cartItem.productDetails && cartItem.productDetails.requiresPrescription === true));
      
      // If any item requires a prescription, set the flag
      if (needsPrescription) {
        requiresPrescription = true;
        console.log(`Item ${itemId || 'unknown'} requires a prescription`, {
          itemId,
          cartItemId: cartItem.id,
          itemRequires: item ? item.requiresPrescription : 'no item',
          cartItemRequires: cartItem.requiresPrescription,
          productDetailsRequires: cartItem.productDetails ? cartItem.productDetails.requiresPrescription : 'no productDetails'
        });
      }
      
      return {
        ...cartItem,
        requiresPrescription: needsPrescription,
        // Ensure productDetails is properly set if not present
        productDetails: cartItem.productDetails || (item ? {
          _id: item._id,
          name: item.name,
          requiresPrescription: item.requiresPrescription
        } : null)
      };
    });
    
    console.log('Prescription required for order:', requiresPrescription);
    
    return {
      requiresPrescription,
      items: updatedItems
    };
  } catch (error) {
    console.error('Error in checkPrescriptionRequirements:', error);
    // In case of error, assume prescription is not required to avoid blocking orders
    return {
      requiresPrescription: false,
      items: items.map(item => ({
        ...item,
        requiresPrescription: false
      }))
    };
  }
};

// @desc    Create new order with optional prescription upload
// @route   POST /api/v1/orders
// @access  Private
exports.createOrder = asyncHandler(async (req, res, next) => {
  const files = req.files || [];
  const {
    items,
    deliveryAddress,
    paymentMethod: rawPaymentMethod = 'cod',
    paymentId,
    notes,
    prescriptionId,
    store = 'default-store',
    coupon,
    ...rest
  } = req.body;
  
  // Initialize orderData object with request body and default values
  const orderData = {
    ...req.body,
    items: [],
    status: 'pending',
    paymentStatus: 'pending',
    statusHistory: [{
      status: 'pending',
      changedAt: new Date(),
      comment: 'Order created',
      changedBy: req.user?._id || null
    }],
    ...rest
  };
  
  // Ensure payment method is valid (normalize to lowercase and check against enum)
  // Normalize payment method (map 'cash' to 'cod' for backward compatibility)
  const paymentMethod = rawPaymentMethod.toLowerCase() === 'cash' ? 'cod' : rawPaymentMethod.toLowerCase();
  
  // Define valid payment methods (must match the Order model's enum)
  const validPaymentMethods = ['cod', 'online', 'wallet'];
  
  // Map frontend payment methods to backend format
  const paymentMethodMap = {
    'cod': 'cod',
    'online': 'online',
    'card': 'online',
    'upi': 'online',
    'netbanking': 'online',
    'wallet': 'wallet'
  };

  // Validate payment method
  if (!validPaymentMethods.includes(paymentMethod in paymentMethodMap ? paymentMethodMap[paymentMethod] : paymentMethod)) {
    return next(new ErrorResponse(`Invalid payment method. Must be one of: ${validPaymentMethods.join(', ')}`, 400));
  }

  // Get the backend payment method
  const backendPaymentMethod = paymentMethodMap[paymentMethod] || 'online';

  // Validate required fields
  // Check if items exist
  if (!items || items.length === 0) {
    return next(new ErrorResponse('Please add at least one item to the order', 400));
  }

  // Validate store ID
  if (store && store !== 'default-store' && !mongoose.Types.ObjectId.isValid(store)) {
    console.error('Invalid store ID format:', store);
    return next(new ErrorResponse('Invalid store information', 400));
  }

  // Set default store if not provided
  if (!store) {
    store = 'default-store';
  }

  // Check if any items require a prescription
  const { requiresPrescription, items: updatedItems } = await checkPrescriptionRequirements(items);
  const actuallyRequiresPrescription = requiresPrescription && updatedItems && updatedItems.some(item => item && item.requiresPrescription);
  
  // Log the prescription requirements check
  console.log('Prescription requirements check:', {
    requiresPrescription,
    hasPrescriptionId: !!prescriptionId,
    prescriptionId,
    items: updatedItems ? updatedItems.map(i => ({
      id: i.item?.toString(),
      name: i.name,
      requiresPrescription: i.requiresPrescription,
      item: i.item,
      productDetails: i.productDetails
    })) : []
  });
  
  console.log('Items requiring prescription:', updatedItems ? updatedItems.filter(i => i.requiresPrescription).length : 0);
  
  // Update orderData with items
  if (updatedItems) {
    orderData.items = updatedItems;
  }
  
  // Initialize prescription status if needed
  if (actuallyRequiresPrescription) {
    // Set default prescription status
    orderData.prescriptionStatus = 'pending';
    orderData.status = 'PENDING_VERIFICATION';
    
    // Add status history entry
    orderData.statusHistory = orderData.statusHistory || [];
    orderData.statusHistory.push({
      status: 'PENDING_VERIFICATION',
      changedAt: new Date(),
      comment: 'Prescription required, pending upload',
      changedBy: req.user?._id || null
    });
    
    // If we have a prescription ID, use it
    if (prescriptionId && prescriptionId !== 'undefined') {
      orderData.prescriptionId = prescriptionId;
      
      // Initialize prescription data if not already set
      if (!orderData.prescription) {
        orderData.prescription = {
          status: 'pending',
          is_verified: false,
          verification_history: [{
            status: 'pending',
            changedAt: new Date(),
            notes: 'Prescription uploaded with order',
            changed_by: req.user?._id?.toString() || 'system'
          }]
        };
      }
      
      // Update the status history
      orderData.statusHistory.push({
        status: 'PENDING_VERIFICATION',
        changedAt: new Date(),
        comment: 'Prescription uploaded, pending verification',
        changedBy: req.user?._id || null
      });
    } else if (req.body.prescriptions && req.body.prescriptions.length > 0) {
      // If we have prescription files in the request
      console.log('Processing prescription files from request');
      
      // Add status history entry for uploaded files
      orderData.statusHistory.push({
        status: 'PENDING_VERIFICATION',
        changedAt: new Date(),
        comment: 'Prescription files uploaded, pending verification',
        changedBy: req.user?._id || null
      });
    } else {
      console.log('Prescription required but not yet provided, setting pending status');
      
      // Set default status to indicate prescription is pending
      orderData.prescriptionStatus = 'pending';
      orderData.status = 'PENDING_VERIFICATION';
      
      // Initialize prescription data
      orderData.prescription = {
        status: 'pending',
        is_verified: false,
        verification_history: [{
          status: 'pending',
          changedAt: new Date(),
          notes: 'Prescription required but not yet provided',
          changed_by: req.user?._id?.toString() || 'system'
        }]
      };
      
      // Add status history
      orderData.statusHistory = orderData.statusHistory || [];
      orderData.statusHistory.push({
        status: 'PENDING_VERIFICATION',
        changedAt: new Date(),
        comment: 'Prescription required but not yet provided',
        changedBy: req.user?._id || null
      });
    }
  }

  // Update the items with prescription requirements
  req.body.items = updatedItems;
  
  
  // If prescription is provided, verify it exists and belongs to the user or is a temporary ID
  let prescription = null;
  
  // Define required prescription fields and their validation
  const requiredPrescriptionFields = [
    { field: 'doctor_name', type: 'string', required: true },
    { field: 'patient_name', type: 'string', required: true },
    { field: 'patient_age', type: 'number', required: true, min: 1, max: 120 },
    { field: 'patient_gender', type: 'string', required: true, enum: ['male', 'female', 'other'] },
    { field: 'prescription_date', type: 'string', required: true }
  ];
  if (prescriptionId && prescriptionId !== 'undefined') {
    // Check if it's a temporary ID (starts with 'temp_' or 'temp-')
    if (prescriptionId.startsWith('temp_') || prescriptionId.startsWith('temp-')) {
      console.log('Using temporary prescription ID:', prescriptionId);
      // For temporary IDs, we need to validate the prescription data
      if (!req.body.prescription) {
        console.error('Prescription data is required for temporary IDs');
        return next(new ErrorResponse('Prescription data is required', 400));
      }
      
      // Validate and normalize prescription data
      const prescriptionData = { ...req.body.prescription };
      
      // Validate required fields and their types
      const validationErrors = [];
      
      requiredPrescriptionFields.forEach(({ field, type, required, min, max, enum: enumValues }) => {
        const value = prescriptionData[field];
        
        // Check required fields
        if (required && (value === undefined || value === null || value === '')) {
          validationErrors.push(`'${field}' is required`);
          return;
        }
        
        // Skip further validation if value is not provided
        if (value === undefined || value === null) return;
        
        // Type checking
        if (type === 'number' && isNaN(Number(value))) {
          validationErrors.push(`'${field}' must be a number`);
        } else if (type === 'string' && typeof value !== 'string') {
          validationErrors.push(`'${field}' must be a string`);
        }
        
        // Range validation for numbers
        if (type === 'number' && (min !== undefined || max !== undefined)) {
          const numValue = Number(value);
          if (min !== undefined && numValue < min) {
            validationErrors.push(`'${field}' must be at least ${min}`);
          }
        }
      }); // Close the forEach callback and its parenthesis
      
      // Check if there were any validation errors
      if (validationErrors.length > 0) {
        return next(new ErrorResponse(`Invalid prescription data: ${validationErrors.join('; ')}`, 400));
      }
      
      // If we get here, the prescription data is valid
      // Prepare the prescription data to be embedded in the order
      try {
        // Get the uploaded file path if available
        const uploadedFilePath = file ? file.path : '';
        const uploadedFileName = file ? file.filename : '';
        
        const prescriptionDataToSave = {
          doctor_name: prescriptionData.doctor_name,
          // Add other prescription fields here
          patient_name: prescriptionData.patient_name || '',
          patient_age: prescriptionData.patient_age || null,
          patient_gender: prescriptionData.patient_gender || 'other',
          prescription_date: prescriptionData.prescription_date || new Date(),
          status: 'pending',
          is_verified: false,
          verification_method: 'manual',
          images: [] // Will be populated with uploaded files
        };
        
        // Process any uploaded files
        if (req.files && req.files.length > 0) {
          prescriptionDataToSave.images = req.files.map(file => ({
            path: `/uploads/prescriptions/${file.filename}`,
            original_name: file.originalname,
            mimetype: file.mimetype,
            size: file.size,
            is_primary: true,
            uploaded_at: new Date()
          }));
        }
        
        return prescriptionDataToSave;
      } catch (error) {
        console.error('Error preparing prescription data:', error);
        return next(new ErrorResponse('Failed to process prescription data', 500));
      }
    } else if (actuallyRequiresPrescription && !prescriptionId) {
      // No valid prescription ID provided but prescription is required
      console.error('Prescription required but not provided:', { 
        prescriptionId,
        actuallyRequiresPrescription,
        hasPrescription: !!prescriptionId,
        itemsRequiringPrescription: updatedItems
          .filter(item => item.requiresPrescription)
          .map(item => ({
            id: item.id || item._id,
            name: item.name,
            requiresPrescription: item.requiresPrescription
          }))
      });
      return next(new ErrorResponse('A valid prescription is required for one or more items in your order', 400));
    }
  }
  
  // Update items with prescription requirements
  req.body.items = updatedItems;
  
  // Generate order number
  const orderNumber = `ORD-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
  
  // Get store from the first item in the order
  let storeId = null;
  let storeDetails = null;
  
  // Log the incoming request data for debugging
  console.log('Order items for store resolution:', JSON.stringify(updatedItems, null, 2));
  
  // Try to get store from the first item
  if (updatedItems && updatedItems.length > 0) {
    const firstItem = updatedItems[0];
    if (firstItem) {
      console.log('First item data:', JSON.stringify(firstItem, null, 2));
      
      // 0. First check if storeId is directly in the item (from cart)
      if (firstItem.storeId) {
        storeId = firstItem.storeId._id || firstItem.storeId;
        console.log(`0. Using store from item.storeId: ${storeId}`);
      }
      
      // 1. Try to get store from the product data in the request
      if (!storeId && firstItem.product) {
        // Check for store_id in product data (nested or direct)
        if (firstItem.product.store_id) {
          // Handle both nested and direct store_id formats
          const storeRef = firstItem.product.store_id;
          storeId = storeRef._id || storeRef;
          console.log(`1. Using store from item.product.store_id: ${storeId}`);
        }
        
        // If still no store ID, check for product.store
        if (!storeId && firstItem.product.store) {
          const storeRef = firstItem.product.store;
          storeId = storeRef._id || storeRef;
          console.log(`1.1 Using store from item.product.store: ${storeId}`);
        }
      }
      
      // 2. If still no store ID, try to get it from the database using product ID
      if (!storeId && firstItem.product?._id) {
        try {
          const product = await Product.findById(firstItem.product._id)
            .select('store_id store')
            .populate('store_id', 'name address');
            
          if (product) {
            // Try store_id first
            if (product.store_id) {
              storeId = product.store_id._id || product.store_id;
              storeDetails = product.store_id;
              console.log(`2. Fetched store_id from database for product ${firstItem.product._id}: ${storeId}`);
              
              // Update the product data with the store ID for future reference
              if (firstItem.product && !firstItem.product.store_id) {
                firstItem.product.store_id = product.store_id;
              }
            }
            
            // If still no store ID, try the store field
            if (!storeId && product.store) {
              storeId = product.store._id || product.store;
              storeDetails = product.store;
              console.log(`2.1 Fetched store from database for product ${firstItem.product._id}: ${storeId}`);
            }
          }
        } catch (error) {
          console.error('Error fetching product store info:', error);
        }
      }
      
      // 3. If we have a store ID but no details, fetch the store details
      if (storeId && !storeDetails) {
        try {
          const store = await Store.findById(storeId).select('name address');
          if (store) {
            storeDetails = store;
            console.log(`3. Fetched store details for store ID ${storeId}:`, storeDetails);
          }
        } catch (error) {
          console.error('Error fetching store details:', error);
        }
      }
      
      // 4. If still no store, check the item's store reference directly
      if (!storeId && firstItem.store) {
        storeId = firstItem.store._id || firstItem.store;
        storeDetails = firstItem.store;
        console.log(`4. Using store from item.store: ${storeId}`);
      }
    }
  }
  
  // 5. If still no store ID, fail the order creation
  if (!storeId) {
    return next(new ErrorResponse('Could not determine store for the order. Please ensure all items have a valid store association.', 400));
  }
  
  // Helper function to get nested object properties
  function getNestedValue(obj, path) {
    return path.split('.').reduce((o, p) => o && o[p], obj);
  }
  
  // If still no store, use the store parameter if it's not 'default-store'
  if (store && store !== 'default-store') {
    storeId = store;
    console.log(`Using store from store parameter: ${storeId}`);
  }
  
  // If still no store, try to find the first available active store
  if (!storeId) {
    try {
      const defaultStore = await Store.findOne({ 
        'store.isActive': true,
        status: 'Active'
      }).sort({ createdAt: 1 }).select('_id');
      if (defaultStore) {
        storeId = defaultStore._id;
        console.log(`Using first active store as default: ${storeId}`);
      } else {
        console.error('No active stores found in the system');
        return next(new ErrorResponse('No active stores available', 400));
      }
    } catch (error) {
      console.error('Error finding default store:', error);
      return next(new ErrorResponse('Failed to determine store for order', 500));
    }
  }
  
  // Ensure storeId is a valid ObjectId
  if (!storeId || !mongoose.Types.ObjectId.isValid(storeId)) {
    console.error('Invalid store ID format or missing store ID:', storeId);
    
    // Try to get store from the first product in the order
    if (updatedItems && updatedItems.length > 0) {
      // First, try to get store from product data in the first item
      const firstItem = updatedItems[0];
      const product = firstItem.product || {};
      
      console.log('Product data in order item:', JSON.stringify(product, null, 2));
      
      // Try to get store from product.store_id (could be _id or object with _id)
      if (product.store_id) {
        storeId = product.store_id._id || product.store_id;
        console.log(`Using store from product.store_id: ${storeId}`);
      } 
      // Try to get store from product.store if store_id is not available
      else if (product.store) {
        storeId = product.store._id || product.store;
        console.log(`Using store from product.store: ${storeId}`);
      }
      // If still no store, try to get it directly from the database
      else if (product._id) {
        try {
          const dbProduct = await Product.findById(product._id).select('store_id');
          if (dbProduct && dbProduct.store_id) {
            storeId = dbProduct.store_id._id || dbProduct.store_id;
            console.log(`Fetched store from database for product ${product._id}: ${storeId}`);
          }
        } catch (error) {
          console.error('Error fetching product store info:', error);
        }
      }
      
      // If we still don't have a store ID, check if the item has store information directly
      if (!storeId && firstItem.store_id) {
        storeId = firstItem.store_id._id || firstItem.store_id;
        console.log(`Using store from item.store_id: ${storeId}`);
      }
    }
    
    // If still no store ID, try to get a default store
    if (!storeId) {
      try {
        const defaultStore = await Store.findOne({ isDefault: true }).select('_id name address');
        if (defaultStore) {
          storeId = defaultStore._id;
          console.log(`Using default store as fallback: ${storeId}`);
        } else {
          const firstStore = await Store.findOne().select('_id name address');
          if (firstStore) {
            storeId = firstStore._id;
            console.log(`Using first available store as fallback: ${storeId}`);
          } else {
            return next(new ErrorResponse('No stores available', 400));
          }
        }
      } catch (error) {
        console.error('Error finding fallback store:', error);
        return next(new ErrorResponse('Error processing store information', 500));
      }
    }
  }
  
  // Log the store being used for the order
  console.log('Using store for order:', JSON.stringify(storeDetails, null, 2));
  
  // Update order data with store information from product
  if (storeDetails && storeDetails._id) {
    orderData.store = storeDetails._id;
    orderData.storeName = storeDetails.name;
    orderData.storeAddress = storeDetails.address;
    
    // Update store reference in each item
    if (orderData.items && orderData.items.length > 0) {
      orderData.items = orderData.items.map(item => {
        // Preserve the original item data
        const updatedItem = { ...item };
        
        // Ensure the store is set to the correct store ID
        updatedItem.store = storeDetails._id;
        updatedItem.storeName = storeDetails.name;
        
        // Ensure the product data has the correct store ID
        if (updatedItem.product) {
          updatedItem.product.store_id = storeDetails._id;
          updatedItem.product.store = storeDetails;
        }
        
        return updatedItem;
      });
    }
  } else {
    // If no valid store found, fail the order
    return next(new ErrorResponse('No valid store found for the products in this order', 400));
  }
  
  // Calculate total amount
  const totalAmount = updatedItems.reduce((sum, item) => {
    return sum + ((item.price * item.quantity) + (item.taxAmount || 0) - (item.discountAmount || 0));
  }, 0);
  
  // Update the existing orderData object with required fields
  orderData.userId = req.user.id;
  orderData.orderNumber = orderNumber || `ORD-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
  
  // Verify store is set correctly
  if (!orderData.store) {
    return next(new ErrorResponse('No store associated with this order', 400));
  }
  orderData.items = updatedItems.map(item => {
      // Ensure all required fields have values with proper fallbacks
      const itemPrice = Number(item.price) || 0;
      const itemQuantity = Number(item.quantity) || 1;
      const taxAmount = Number(item.taxAmount) || 0;
      const discountAmount = Number(item.discountAmount) || 0;
      
      // Calculate total amount with fallback
      const totalAmount = (itemPrice * itemQuantity) + taxAmount - discountAmount;
      
      // Create the order item with all required fields
      const orderItem = {
        productId: item.id || item._id || item.item || new mongoose.Types.ObjectId(),
        item: item.id || item._id || item.item || new mongoose.Types.ObjectId(),
        name: item.name || 'Unnamed Product',
        price: itemPrice,
        quantity: itemQuantity,
        requiresPrescription: item.requiresPrescription || false,
        image: item.image || (item.images && item.images[0]) || '',
        brand: item.brand || 'Generic',
        category: item.category || 'General',
        unit: item.unit || 'pcs',
        taxAmount: taxAmount,
        discountAmount: discountAmount,
        totalAmount: totalAmount,
        weight: Number(item.weight) || 0,
        sku: item.sku || '',
        barcode: item.barcode || ''
      };
      
      // Log the order item for debugging
      console.log('Creating order item with calculated total:', {
        price: orderItem.price,
        quantity: orderItem.quantity,
        tax: orderItem.taxAmount,
        discount: orderItem.discountAmount,
        total: orderItem.totalAmount
      });
      
      // Log the order item for debugging
      console.log('Creating order item:', JSON.stringify(orderItem, null, 2));
      
      return orderItem;
    });
  
  // Add the rest of the order data
  orderData.totalAmount = totalAmount;
  orderData.finalAmount = totalAmount;
  orderData.paymentId = `pay_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  orderData.paymentMethod = req.body.paymentMethod || 'cod';
  orderData.paymentStatus = 'PENDING';
  orderData.status = 'PENDING';
  orderData.orderStatus = 'pending';
  orderData.deliveryAddress = req.body.deliveryAddress;
  orderData.prescriptionStatus = actuallyRequiresPrescription ? 'pending' : 'not_required';
  
  // Initialize status history if it doesn't exist
  if (!orderData.statusHistory || !Array.isArray(orderData.statusHistory)) {
    orderData.statusHistory = [];
  }
  
  // Add initial status if not already present
  if (!orderData.statusHistory.some(sh => sh.status === 'PENDING')) {
    orderData.statusHistory.push({
      status: 'PENDING',
      changedAt: new Date(),
      comment: 'Order created',
      changedBy: req.user?.id || null
    });
  }
  
  // Add prescription data if available
  if (req.body.prescriptions && req.body.prescriptions.length > 0) {
    // Create prescription object from the first prescription file
    const prescriptionData = req.body.prescriptions[0];
    
    orderData.prescription = {
      images: [{
        path: prescriptionData.fileName,
        is_primary: true,
        uploaded_at: new Date(),
        mimetype: 'image/png', // Default mime type, adjust as needed
        size: 0, // Default size, adjust if available
        original_name: prescriptionData.fileName
      }],
      status: 'pending',
      is_verified: false,
      verification_history: [{
        status: 'pending',
        changedAt: new Date(),
        notes: 'Prescription uploaded with order',
        changed_by: req.user.id
      }],
      prescription_date: new Date(),
      verification_method: 'manual'
    };
    
    // Set prescription status
    orderData.prescriptionStatus = 'pending';
    orderData.status = 'PENDING_VERIFICATION';
    
    // Add status history entry
    orderData.statusHistory = orderData.statusHistory || [];
    orderData.statusHistory.push({
      status: 'PENDING_VERIFICATION',
      changedAt: new Date(),
      comment: 'Prescription uploaded, pending verification',
      changedBy: req.user?.id || null
    });
  }
  
  // Log the incoming order data before any modifications
  console.log('Original order data:', JSON.stringify(orderData, null, 2));
  
  // Store the original store ID from the request body
  const originalStoreId = req.body.store || req.body.storeId;
  
  // Set default values if not provided
  orderData.orderNumber = `ORD-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
  orderData.status = 'PENDING';
  orderData.orderStatus = 'pending';
  orderData.paymentStatus = 'PENDING';
  orderData.statusHistory = [{
    status: 'PENDING',
    changedAt: new Date(),
    comment: 'Order created'
  }];
  
  // Always use the store ID from the request body if it exists
  if (originalStoreId) {
    console.log('Using original store ID from request:', originalStoreId);
    orderData.store = originalStoreId;
    orderData.storeId = originalStoreId;
  }
  
  // Add prescription data if required
  if (actuallyRequiresPrescription) {
    // If we have a prescription ID, use that
    if (prescriptionId && prescriptionId !== 'undefined') {
      orderData.prescriptionId = prescriptionId;
      
      // If we don't have prescription data, add minimal required fields
      if (!orderData.prescription) {
        orderData.prescription = {
          status: 'pending',
          is_verified: false,
          verification_history: [{
            status: 'pending',
            changedAt: new Date(),
            notes: 'Prescription uploaded with order',
            changed_by: req.user?.id || 'system'
          }]
        };
      }
    } else if (req.body.prescription) {
      // If we have full prescription data, use that
      orderData.prescription = {
        ...req.body.prescription,
        status: 'pending',
        is_verified: false,
        verification_history: [{
          status: 'pending',
          changedAt: new Date(),
          notes: 'Prescription uploaded with order',
          changed_by: req.user?.id || 'system'
        }]
      };
    }
    
    if (prescriptionId && !prescriptionId.startsWith('temp_') && !prescriptionId.startsWith('temp-')) {
      orderData.prescriptionId = prescriptionId;
    }
    
    // Set status to pending verification
    orderData.status = 'PENDING_VERIFICATION';
    orderData.prescriptionStatus = 'pending';
  }
  
  // Create the order
  try {
    // First, log the incoming request data for debugging
    console.log('Raw request body:', JSON.stringify(req.body, null, 2));
    console.log('Initial orderData.store:', orderData.store);
    console.log('Initial orderData.storeId:', orderData.storeId);
    
    // If we have prescription data, ensure it's properly formatted
    if (requiresPrescription && req.body.prescription && !orderData.prescription) {
      orderData.prescription = {
        ...req.body.prescription,
        status: 'pending',
        is_verified: false,
        verification_method: 'manual',
        images: Array.isArray(req.body.prescription.images) ? req.body.prescription.images.map(img => ({
          path: img.path || '',
          is_primary: img.is_primary || false,
          mimetype: img.mimetype || 'image/jpeg',
          size: img.size || 0,
          original_name: img.original_name || 'prescription.jpg',
          uploaded_at: img.uploaded_at || new Date()
        })) : []
      };
      
      console.log('Added prescription data to order:', {
        hasImages: orderData.prescription.images.length > 0,
        imageCount: orderData.prescription.images.length,
        status: orderData.prescription.status
      });
    }
    
    // Get store ID from the order data (should already be set from the request body)
    let storeId = orderData.store || orderData.storeId;
    
    // If we still don't have a store ID, try to get it from the first item
    if (!storeId && Array.isArray(orderData.items) && orderData.items.length > 0) {
      const firstItem = orderData.items[0];
      storeId = firstItem.storeId || firstItem.store || (firstItem.store_id ? firstItem.store_id._id || firstItem.store_id : null);
      if (storeId) {
        console.log('Using store ID from first item:', storeId);
      }
    }
    
    // Convert to string and clean up
    storeId = String(storeId || '').trim();
    console.log('Final store ID to use:', storeId);
    
    // Handle default-store case
    if (storeId === 'default-store') {
      console.log('Using default store');
      // Find the first available store to use as default
      const defaultStore = await mongoose.model('Store').findOne().sort({ createdAt: 1 });
      
      if (!defaultStore) {
        console.error('No stores available in the system');
        throw new Error('NO_STORES_AVAILABLE: No stores are configured in the system');
      }
      
      storeId = defaultStore._id;
      console.log('Using default store ID:', storeId);
    } 
    // Validate ObjectId format for non-default stores
    else if (!storeId || !mongoose.Types.ObjectId.isValid(storeId)) {
      console.error('Invalid store ID format:', storeId);
      console.error('Order data:', JSON.stringify(orderData, null, 2));
      throw new Error('INVALID_STORE_ID: Must be a valid MongoDB ObjectId');
    }
    
    // Convert to ObjectId and validate store exists
    try {
      const storeObjectId = new mongoose.Types.ObjectId(storeId);
      const store = await mongoose.model('Store').findById(storeObjectId);
      
      if (!store) {
        console.error(`Store not found: ${storeId}`);
        throw new Error('STORE_NOT_FOUND: The specified store does not exist');
      }
      
      // Log the store validation
      console.log('Validated store:', {
        storeIdFromRequest: storeId,
        storeIdInDatabase: store._id,
        storeName: store.name || 'Unnamed Store'
      });
      
      // Update the order data with the validated store ID
      orderData.store = store._id;
      orderData.storeId = store._id.toString(); // Ensure storeId is a string
      
      // Update items with all required fields
      if (Array.isArray(orderData.items)) {
        orderData.items = orderData.items.map(item => {
          // Calculate total amount for the item if not provided
          const price = Number(item.price) || 0;
          const quantity = Number(item.quantity) || 1;
          const totalAmount = price * quantity;
          
          return {
            ...item,
            productId: item.productId || item.item || item._id, // Use item ID as productId if not provided
            store: store._id,
            storeId: store._id.toString(),
            price: price,
            quantity: quantity,
            totalAmount: totalAmount,
            // Ensure all required fields have default values
            name: item.name || 'Unnamed Product',
            image: item.image || '',
            requiresPrescription: Boolean(item.requiresPrescription)
          };
        });
      }
      
      console.log('Using store:', { 
        id: store._id, 
        name: store.name || 'Unnamed Store',
        storeIdFromRequest: storeId,
        storeIdInOrder: orderData.store.toString()
      });
    } catch (error) {
      console.error('Error validating store:', error);
      // Forward the original error message to the client
      throw new Error(error.message || 'STORE_VALIDATION_ERROR: Error validating store');
    }
    
    // Process items to ensure they have the correct structure
    if (Array.isArray(orderData.items)) {
      orderData.items = orderData.items.map(item => {
        // Ensure item has the correct store ID
        if (!item.store) {
          console.log('Adding store ID to item:', { 
            itemId: item.item || item._id, 
            store: orderData.store 
          });
          item.store = orderData.store;
        }
        
        return {
          store: orderData.store, // Use the validated store ID from the order
          name: item.name,
          price: item.price,
          quantity: item.quantity,
          image: item.image,
          requiresPrescription: Boolean(item.requiresPrescription),
          item: mongoose.Types.ObjectId.isValid(item.item) ? item.item : item._id,
          store: orderData.store, // Use the order's store ID for all items
          product: item.product || item.item,
          product_id: item.product_id || item.item
        };
      });
    }
    
    // Ensure the user ID is a valid ObjectId
    if (orderData.userId && !mongoose.Types.ObjectId.isValid(orderData.userId)) {
      console.warn('Invalid user ID:', orderData.userId);
      orderData.userId = null; // Or handle guest orders appropriately
    }
    
    // Add order number if not present
    if (!orderData.orderNumber) {
      orderData.orderNumber = `ORD-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
    }
    
    // Log the final order data before saving
    console.log('Final order data before save:', JSON.stringify({
      ...orderData,
      items: orderData.items.map(i => ({
        productId: i.productId?.toString(),
        item: i.item?.toString(),
        name: i.name,
        quantity: i.quantity,
        price: i.price,
        totalAmount: i.totalAmount,
        requiresPrescription: i.requiresPrescription,
        taxAmount: i.taxAmount,
        discountAmount: i.discountAmount
      }))
    }, null, 2));
    
    console.log('Creating order with data:', JSON.stringify({
      ...orderData,
      items: orderData.items.map(i => ({
        item: i.item?.toString(),
        store: i.store?.toString(),
        name: i.name,
        quantity: i.quantity
      }))
    }, null, 2));
    
    order = await Order.create(orderData);
    console.log(`Created new order with ID: ${order._id} for store: ${order.store}`);
  } catch (error) {
    console.error('Error creating order:', error);
    return next(new ErrorResponse('Failed to create order: ' + error.message, 500));
  }
  
  // Handle prescription if we have one
  if ((prescriptionId && prescriptionId !== 'undefined') || orderData.prescription) {
    console.log('Processing prescription data:', { prescriptionId, hasPrescriptionData: !!orderData.prescription });
    
    // If we have prescription data in the order, use that to create/update prescription
    if (orderData.prescription) {
      try {
        console.log('Creating prescription from order data');
        
        // Ensure uploads directory exists
        const uploadDir = path.join(__dirname, '../uploads/prescriptions');
        if (!fs.existsSync(uploadDir)) {
          fs.mkdirSync(uploadDir, { recursive: true });
        }
        
        // Handle uploaded files from req.files or req.body.files
        let images = [];
        
        // Check for files in req.files (direct multer upload)
        if (req.files && req.files.length > 0) {
          console.log('Processing uploaded files in req.files:', req.files);
          images = await Promise.all(req.files.map(async (file) => {
            // Create a unique filename
            const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
            const ext = path.extname(file.originalname).toLowerCase();
            const fileName = 'rx-' + uniqueSuffix + ext;
            const filePath = path.join(uploadDir, fileName);
            
            // Move the file from temp location to uploads directory
            await fs.promises.rename(file.path, filePath);
            
            return {
              path: `/uploads/prescriptions/${fileName}`,
              original_name: file.originalname,
              mimetype: file.mimetype,
              size: file.size,
              is_primary: true,
              uploaded_at: new Date()
            };
          }));
        } 
        // Check for files in req.body.files (from the route middleware)
        else if (req.body.files && req.body.files.length > 0) {
          console.log('Processing files from req.body.files:', req.body.files);
          images = req.body.files.map(file => ({
            path: `/uploads/prescriptions/${file.filename}`,
            original_name: file.originalname,
            mimetype: file.mimetype,
            size: file.size,
            is_primary: true,
            uploaded_at: new Date()
          }));
        }
        // Handle base64 image data if present in prescription
        else if (orderData.prescription && orderData.prescription.file) {
          console.log('Processing base64 image from prescription data');
          try {
            const base64Data = orderData.prescription.file.split(';base64,').pop();
            const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
            const fileName = `rx-${uniqueSuffix}.jpg`;
            const filePath = path.join(uploadDir, fileName);
            
            // Save the file
            await fs.promises.writeFile(filePath, base64Data, { encoding: 'base64' });
            
            // Add to images array
            images.push({
              path: `/uploads/prescriptions/${fileName}`,
              original_name: orderData.prescription.fileName || 'prescription.jpg',
              mimetype: orderData.prescription.fileType || 'image/jpeg',
              size: Buffer.byteLength(base64Data, 'base64'),
              is_primary: true,
              uploaded_at: new Date()
            });
          } catch (error) {
            console.error('Error processing base64 image:', error);
            // Continue with empty images array if there's an error
          }
        }
        
        // Create prescription record
        const prescriptionData = {
          userId: orderData.userId,
          storeId: orderData.storeId || orderData.store, // Use storeId from order
          orderId: order._id, // Set the order ID immediately since we have it now
          doctor_name: orderData.prescription.doctor_name || 'Not specified',
          patient_name: orderData.prescription.patient_name || orderData.deliveryAddress?.name || 'Customer',
          patient_age: orderData.prescription.patient_age || null,
          patient_gender: orderData.prescription.patient_gender || 'other',
          prescription_date: orderData.prescription.prescription_date || new Date(),
          status: 'pending',
          is_verified: false,
          verification_method: 'manual',
          images: images.length > 0 ? images : (orderData.prescription.images || []),
          items: [{
            productId: orderData.prescription.productId,
            productName: orderData.prescription.productName || 'Prescription Item',
            quantity: 1
          }]
        };
        
        console.log('Creating prescription with data:', JSON.stringify(prescriptionData, null, 2));
        
        const prescription = await Prescription.create(prescriptionData);
        console.log('Prescription created:', prescription._id);
        
        // Convert the prescription to a plain object to ensure we get all fields
        const prescriptionObj = prescription.toObject ? prescription.toObject() : prescription;
        
        // Update the order with the prescription ID, status, and images
        order.prescriptionId = prescription._id;
        order.prescriptionStatus = 'pending';
        
        // Ensure the prescription object exists on the order
        if (!order.prescription) {
          order.prescription = {};
        }
        
        // Update the order's prescription data with the created prescription
        order.prescription = {
          ...order.prescription, // Preserve existing prescription data
          ...prescriptionObj, // Spread all prescription fields
          images: [...(prescriptionObj.images || [])], // Create a new array with prescription images
          _id: prescriptionObj._id,
          createdAt: prescriptionObj.createdAt,
          updatedAt: prescriptionObj.updatedAt,
          is_verified: false,
          verification_method: 'manual',
          status: 'pending'
        };
        
        console.log('Updated order prescription with images:', order.prescription.images);
        
        // Add status history if not already added
        const hasVerificationStatus = order.statusHistory.some(
          h => h.comment === 'Prescription uploaded, pending verification'
        );
        
        if (!hasVerificationStatus) {
          order.statusHistory.push({
            status: 'PENDING_VERIFICATION',
            changedAt: new Date(),
            comment: 'Prescription uploaded, pending verification',
            changedBy: order.userId
          });
        }
        
        // Mark the prescription field as modified to ensure it gets saved
        order.markModified('prescription');
        order.markModified('statusHistory');
        
        // Save the updated order
        await order.save();
        
        // Fetch the updated order to ensure we have the latest data
        const updatedOrder = await Order.findById(order._id);
        
        console.log(`Updated order ${updatedOrder._id} with prescription ID: ${prescription._id}`, {
          orderPrescriptionImages: updatedOrder.prescription?.images,
          prescriptionImages: prescription.images
        });
      } catch (error) {
        console.error('Error creating prescription from order data:', error);
        // Don't fail the order if prescription creation fails
      }
    } 
    // For temporary prescription IDs (from frontend), we need to create a new prescription
    else if (prescriptionId.startsWith('temp_') || prescriptionId.startsWith('temp-')) {
      console.log('Handling temporary prescription ID:', prescriptionId);
      
      // Get the prescription data from the request body
      const { prescription } = req.body;
      if (!prescription) {
        return next(new ErrorResponse('Prescription data is required', 400));
      }
      
      try {
        // Log the incoming prescription data for debugging
        console.log('Processing prescription data:', JSON.stringify(prescription, null, 2));
        
        // Get the first image URL from the prescription data
        let imageUrl = null;
        
        // Check different possible locations for the image URL
        if (prescription.images && Array.isArray(prescription.images) && prescription.images.length > 0) {
          // If images array exists, get the first image's URL
          const firstImage = prescription.images[0];
          imageUrl = firstImage.url || firstImage.path || 
                    (firstImage.filename ? `/uploads/prescriptions/${firstImage.filename}` : null);
          console.log('Found image in prescription.images:', { imageUrl, firstImage });
        } 
        else if (prescription.files && Array.isArray(prescription.files) && prescription.files.length > 0) {
          // If files array exists, get the first file's URL
          const firstFile = prescription.files[0];
          imageUrl = firstFile.url || firstFile.path || 
                    (firstFile.filename ? `/uploads/prescriptions/${firstFile.filename}` : null);
          console.log('Found image in prescription.files:', { imageUrl, firstFile });
        } 
        else if (prescription.imageUrl) {
          // If imageUrl is directly in the prescription object
          imageUrl = prescription.imageUrl;
          console.log('Found direct imageUrl:', imageUrl);
        } 
        else if (prescription.data) {
          // If there's a data object, check for files or fileUrls
          if (prescription.data.files && Array.isArray(prescription.data.files) && prescription.data.files.length > 0) {
            const firstFile = prescription.data.files[0];
            imageUrl = firstFile.url || firstFile.path || 
                      (firstFile.filename ? `/uploads/prescriptions/${firstFile.filename}` : null);
            console.log('Found image in prescription.data.files:', { imageUrl, firstFile });
          } 
          else if (prescription.data.fileUrls && Array.isArray(prescription.data.fileUrls) && prescription.data.fileUrls.length > 0) {
            imageUrl = prescription.data.fileUrls[0];
            console.log('Found image in prescription.data.fileUrls:', imageUrl);
          }
        }
        
        // If we still don't have an image URL, check for any other possible locations
        if (!imageUrl) {
          // Check if there's a single file in the root of the prescription
          if (prescription.url) {
            imageUrl = prescription.url;
            console.log('Found image in root prescription.url:', imageUrl);
          } 
          else if (prescription.path) {
            imageUrl = prescription.path;
            console.log('Found image in root prescription.path:', imageUrl);
          }
        }

        if (!imageUrl) {
          console.error('No valid image URL found in prescription data:', JSON.stringify(prescription, null, 2));
          return next(new ErrorResponse('Prescription image is required', 400));
        }

        // Ensure the image URL is properly formatted
        if (!imageUrl.startsWith('http') && !imageUrl.startsWith('/uploads/')) {
          imageUrl = `/uploads/prescriptions/${imageUrl.split('/').pop()}`;
        }

        console.log('Creating prescription with image URL:', imageUrl);

        // Create the order first
        let order;
        try {
          order = new Order({
            user: req.user._id,
            items: req.body.items,
            totalAmount: req.body.totalAmount,
            couponCode: req.body.couponCode || '',
            paymentMethod: req.body.paymentMethod,
            deliveryAddress: req.body.deliveryAddress,
            status: 'pending',
            prescriptionId: prescriptionId || undefined, // Only set if we have a prescription ID
            prescription: req.body.prescription || undefined // Include prescription data if available
          });

          // Save the order to get the _id
          await order.save();
          console.log(`Created new order with ID: ${order._id}`);
        } catch (error) {
          console.error('Error creating order:', error);
          return next(new ErrorResponse('Failed to create order', 500));
        }

        // Handle prescription if we have one
        if (prescriptionId && prescriptionId !== 'undefined') {
          // For temporary prescription IDs (from frontend), we need to create a new prescription
          if (prescriptionId.startsWith('temp_') || prescriptionId.startsWith('temp-')) {
            console.log('Handling temporary prescription ID:', prescriptionId);
            
            // Get the prescription data from the request body
            const { prescription } = req.body;
            
            if (!prescription) {
              console.error('No prescription data provided for temporary ID');
              return next(new ErrorResponse('Prescription data is required', 400));
            }
            
            try {
              // Create the prescription with the order reference
              const newPrescription = await Prescription.create({
                userId: req.user._id,
                orderId: order._id,
                doctorName: prescription.doctor_name || 'Dr. Unknown',
                patientName: prescription.patient_name || 'Patient Unknown',
                patientAge: prescription.patient_age || 0,
                patientGender: prescription.patient_gender || 'other',
                status: 'pending',
                images: prescription.images || [],
                notes: prescription.notes || '',
                verification_history: [{
                  status: 'pending',
                  changedAt: new Date(),
                  changedBy: req.user._id,
                  notes: 'Created with order'
                }]
              });
              
              // Update the order with the new prescription ID
              order.prescriptionId = newPrescription._id;
              await order.save();
              
              console.log(`Created new prescription with ID: ${newPrescription._id} for order ${order._id}`);
            } catch (error) {
              console.error('Error creating prescription:', error);
              // Don't fail the order if prescription creation fails
              // Just log the error and continue with the order
            }
          } else {
            // For existing prescription IDs, update the prescription with the order ID
            try {
              await Prescription.findByIdAndUpdate(
                prescriptionId,
                { 
                  orderId: order._id,
                  status: 'pending',
                  $addToSet: { 
                    verification_history: {
                      status: 'pending',
                      changedAt: new Date(),
                      changedBy: req.user._id,
                      notes: 'Linked to order'
                    }
                  }
                },
                { new: true, runValidators: true }
              );
              console.log(`Updated prescription ${prescriptionId} with order ID ${order._id}`);
            } catch (error) {
              console.error('Error updating prescription with order ID:', error);
              // Don't fail the order if prescription update fails
            }
          }
        }
      } catch (error) {
        console.error('Error processing prescription:', error);
        return next(new ErrorResponse('Failed to process prescription', 500));
      }
    } else if (prescriptionId && prescriptionId !== 'undefined') {
      // For existing prescription IDs, update the order and prescription
      try {
        // Update the prescription with the order ID
        await Prescription.findByIdAndUpdate(
          prescriptionId,
          { 
            orderId: order._id,
            status: 'pending',
            $addToSet: { 
              verification_history: {
                status: 'pending',
                changedAt: new Date(),
                changedBy: req.user._id,
                notes: 'Linked to order'
              }
            }
          },
          { new: true, runValidators: true }
        );
        
        // Update the order with the prescription ID
        order.prescriptionId = prescriptionId;
        await order.save();
        
        console.log(`Updated prescription ${prescriptionId} with order ID ${order._id}`);
      } catch (error) {
        console.error('Error updating prescription with order ID:', error);
        // Don't fail the order if prescription update fails
      }
    }
  }

  // Check if we have a valid order
  if (!order) {
    console.error('Order was not created successfully');
    return next(new ErrorResponse('Failed to create order', 500));
  }
  
  // Populate the order with related data
  try {
    order = await Order.findById(order._id)
      .populate('items.item', 'name price image')
      .populate('store', 'name address')
      .populate('userId', 'name email phone')
      .lean();
  } catch (error) {
    console.error('Error populating order:', error);
    // Continue with unpopulated order if population fails
  }

  // Populate the order with necessary data before sending the response
  try {
    const populatedOrder = await Order.findById(order._id)
      .populate('items.item', 'name price image')
      .populate('store', 'name address')
      .populate('userId', 'name email phone')
      .lean();

    // Format the response
    res.status(201).json({
      success: true,
      message: 'Order created successfully',
      data: {
        order: {
          ...populatedOrder,
          orderId: populatedOrder._id, // Add orderId alias for backward compatibility
          id: populatedOrder._id, // Add id alias for backward compatibility
          _id: populatedOrder._id, // Keep the original _id
        }
      }
    });
  } catch (error) {
    console.error('Error populating order:', error);
    // If population fails, still return the order with basic info
    res.status(201).json({
      success: true,
      message: 'Order created successfully',
      data: {
        order: {
          ...order.toObject(),
          orderId: order._id,
          id: order._id
        }
      }
    });
  }
  
  return; // Important: Make sure to return after sending the response
  
  if (!deliveryAddress) {
    return next(new ErrorResponse('Please provide delivery address', 400));
  }

  // Validate required address fields
  const requiredAddressFields = ['name', 'address', 'city', 'state'];
  const missingAddressFields = requiredAddressFields.filter(field => !deliveryAddress[field]);
  
  if (missingAddressFields.length > 0) {
    return next(new ErrorResponse(
      `Missing required address fields: ${missingAddressFields.join(', ')}`,
      400
    ));
  }
  
  // Handle postal code - use existing or set default
  if (deliveryAddress.postcode) {
    deliveryAddress.postalCode = deliveryAddress.postcode;
    delete deliveryAddress.postcode;
  }
  
  // Set default postal code if empty or invalid
  if (!deliveryAddress.postalCode || !/^[1-9][0-9]{5}$/.test(deliveryAddress.postalCode)) {
    deliveryAddress.postalCode = '000000';
  }

  // Validate items
  const invalidItems = items.filter(item => !item.id || !item.name || !item.price || !item.quantity);
  if (invalidItems.length > 0) {
    return next(new ErrorResponse(
      'One or more items are missing required fields (id, name, price, or quantity)',
      400
    ));
  }

  // Calculate order totals
  const subtotal = items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
  const taxAmount = items.reduce((sum, item) => sum + (item.taxAmount || 0), 0);
  const itemDiscounts = items.reduce((sum, item) => sum + (item.discountAmount || 0), 0);
  
  // Use the discount amount from frontend if provided, otherwise calculate it
  let couponDiscount = 0;
  if (coupon) {
    // If frontend sent appliedDiscount, use that directly
    if (coupon.appliedDiscount !== undefined) {
      couponDiscount = parseFloat(coupon.appliedDiscount) || 0;
    } else if (coupon.type === 'percentage') {
      couponDiscount = (subtotal * coupon.discount) / 100;
      // Apply max discount limit if specified
      if (coupon.maxDiscount && couponDiscount > coupon.maxDiscount) {
        couponDiscount = coupon.maxDiscount;
      }
    } else {
      couponDiscount = parseFloat(coupon.discount) || 0;
    }
    // Ensure coupon discount doesn't exceed order subtotal
    couponDiscount = Math.min(couponDiscount, subtotal);
  }
  
  // Use the totalPrice from frontend if provided, otherwise calculate it
  const orderTotalAmount = req.body.totalPrice !== undefined ? 
    parseFloat(req.body.totalPrice) : subtotal;
    
  // Use the discountAmount from frontend if provided, otherwise calculate it
  const discountAmount = req.body.discountAmount !== undefined ?
    parseFloat(req.body.discountAmount) : (itemDiscounts + couponDiscount);
    
  const finalAmount = req.body.totalPrice !== undefined ? 
    parseFloat(req.body.totalPrice) : Math.max(0, subtotal + taxAmount - discountAmount);

  // Use the already determined backend payment method from above

  // Get store information from the first item in the order
  const firstItem = items[0];
  const orderStore = firstItem?.storeId || store;
  const orderStoreName = firstItem?.storeName || 'Default Store';
  
  // We already have requiresPrescription and updatedItems from earlier in the function
  // No need to call checkPrescriptionRequirements again
  
  // If prescription is required, ensure we have the prescription data
  if (requiresPrescription && prescriptionId && req.body.prescription) {
    // Add the prescription data to the order
    orderData.prescription = {
      ...req.body.prescription,
      status: 'pending',
      is_verified: false,
      verification_method: 'manual'
    };
    
    // Set the prescription status
    orderData.prescriptionStatus = 'pending';
    
    // Log the prescription data being added to the order
    console.log('Adding prescription data to order:', JSON.stringify(orderData.prescription, null, 2));
  }

  // Process payment
  let payment;
  try {
    payment = await processPayment({
      amount: totalAmount,
      paymentMethod: { 
        type: paymentMethod || 'online', 
        id: paymentId 
      }
    });
    
    // If we have prescription data, make sure it's properly formatted before order creation
    if (requiresPrescription && req.body.prescription) {
      // Ensure the prescription data has all required fields
      orderData.prescription = {
        ...req.body.prescription,
        status: 'pending',
        is_verified: false,
        verification_method: 'manual',
        images: Array.isArray(req.body.prescription.images) ? req.body.prescription.images.map(img => ({
          path: img.path || '',
          is_primary: img.is_primary || false,
          mimetype: img.mimetype || 'image/jpeg',
          size: img.size || 0,
          original_name: img.original_name || 'prescription.jpg',
          uploaded_at: img.uploaded_at || new Date()
        })) : []
      };
      
      console.log('Processed prescription data for order:', JSON.stringify({
        ...orderData.prescription,
        images: orderData.prescription.images.map(i => i.path)
      }, null, 2));
    }
    
  } catch (error) {
    console.error('Error processing payment:', error);
    return next(new ErrorResponse(`Payment processing failed: ${error.message}`, 400));
  }

  // Prepare order items with all necessary details
  const orderItems = items.map(item => ({
    item: item._id || item.id,
    productId: item._id || item.id,
    name: item.name,
    price: item.price,
    quantity: item.quantity,
    requiresPrescription: item.requiresPrescription || false,
    image: item.images?.[0] || item.image || '',
    brand: item.brand || 'Generic',
    category: item.category || 'General',
    unit: item.unit || 'pcs',
    taxAmount: item.taxAmount || 0,
    discountAmount: item.discountAmount || 0,
    totalAmount: (item.price * item.quantity) + (item.taxAmount || 0) - (item.discountAmount || 0),
    storeName: item.storeName || orderStoreName,
    store: item.storeId || orderStore,
    weight: item.weight || 0,
    variantId: item.variantId || null
  }));

  // Calculate order totals
  const calculatedTotals = orderItems.reduce((acc, item) => ({
    subtotal: acc.subtotal + (item.price * item.quantity),
    tax: acc.tax + (item.taxAmount || 0),
    discount: acc.discount + (item.discountAmount || 0),
    total: acc.total + item.totalAmount
  }), { subtotal: 0, tax: 0, discount: 0, total: 0 });

  // Update the order with payment and other details
  try {
    // Process payment based on method
    let payment;
    if (req.body.paymentMethod === 'online') {
      // Process online payment
      payment = await processPayment({
        amount: order.finalAmount * 100, // Convert to paise
        currency: 'INR',
        receipt: `order_${order._id}`,
        payment_capture: 1
      });
      
      // Update order with payment details
      order.paymentId = payment.id;
      order.paymentStatus = 'PENDING';
      order.status = 'PENDING_PAYMENT';
      
      // Add to status history
      order.statusHistory.push({
        status: 'PENDING_PAYMENT',
        changedAt: new Date(),
        comment: 'Waiting for payment confirmation'
      });
    } else {
      // For COD, create a payment object
      payment = {
        id: `cod_${Date.now()}`,
        status: 'pending',
        amount: order.finalAmount,
        currency: 'INR',
        method: 'cod',
        order_id: order._id
      };
      
      // Update order with payment details
      order.paymentId = payment.id;
      order.paymentStatus = 'PENDING';
      order.status = actuallyRequiresPrescription ? 'PENDING_VERIFICATION' : 'CONFIRMED';
      
      // Add to status history
      order.statusHistory.push({
        status: order.status,
        changedAt: new Date(),
        comment: actuallyRequiresPrescription 
          ? 'Order received, pending prescription verification' 
          : 'Order confirmed, waiting to be processed'
      });
    }
    
    // Save the updated order
    await order.save();
  } catch (error) {
    console.error('Error processing order:', error);
    return next(new ErrorResponse(`Order processing failed: ${error.message}`, 500));
  }
});

// @route   PUT /api/v1/orders/:id
// @access  Private/Admin
exports.updateOrder = asyncHandler(async (req, res, next) => {
  const { status, deliveryBoy, ...otherFields } = req.body;
  
  // Find the order first
  const order = await Order.findById(req.params.id);

  if (!order) {
    return next(
      new ErrorResponse(`Order not found with id of ${req.params.id}`, 404)
    );
  }

  // Update fields if they are provided
  if (status) {
    await Order.updateStatus(order._id, status, { 
      updatedBy: req.user.id,
      comment: 'Order status updated by admin'
    });
  }

  if (deliveryBoy) {
    await order.assignDeliveryBoy(deliveryBoy);
  }

  // Update any other fields
  if (Object.keys(otherFields).length > 0) {
    await order.updateOne(otherFields);
  }

  // Get the updated order
  const updatedOrder = await Order.findById(req.params.id);

  res.status(200).json({ 
    success: true, 
    data: updatedOrder 
  });
});

// @desc    Verify prescription for an order
// @route   PUT /api/v1/orders/:id/verify-prescription
// @access  Private/Admin
exports.verifyPrescription = asyncHandler(async (req, res, next) => {
  const { status, rejectionReason } = req.body;
  
  if (!['approved', 'rejected'].includes(status)) {
    return next(new ErrorResponse('Invalid status. Must be either "approved" or "rejected"', 400));
  }
  
  if (status === 'rejected' && !rejectionReason) {
    return next(new ErrorResponse('Rejection reason is required when rejecting a prescription', 400));
  }
  
  const order = await Order.findById(req.params.id);
  if (!order) {
    return next(new ErrorResponse(`Order not found with id of ${req.params.id}`, 404));
  }
  
  if (!order.prescription.required) {
    return next(new ErrorResponse('This order does not require a prescription', 400));
  }
  
  if (order.prescription.status !== 'pending') {
    return next(new ErrorResponse('Prescription has already been processed', 400));
  }
  
  // Update prescription status
  order.prescription.status = status;
  order.prescription.verified_by = req.user.id;
  order.prescription.verified_at = Date.now();
  
  if (status === 'rejected') {
    order.prescription.rejection_reason = rejectionReason;
    // Optionally, you might want to cancel the order or mark it as on hold
    // order.status = 'cancelled';
  } else {
    // If approved, update order status to processing if it was waiting for prescription
    if (order.status === 'pending') {
      order.status = 'processing';
    }
  }
  
  await order.save();
  
  // Send notification to user
  await Notification.create({
    user: order.user,
    title: `Prescription ${status}`,
    message: `Your prescription for order #${order.orderNumber} has been ${status}.` + 
             (status === 'rejected' ? ` Reason: ${rejectionReason}` : ''),
    type: 'prescription_update',
    referenceId: order._id
  });
  
  res.status(200).json({
    success: true,
    data: order
  });
});

// @desc    Update order status
// @route   PUT /api/v1/orders/:id/status
// @access  Private/Admin
exports.updateOrderStatus = asyncHandler(async (req, res, next) => {
  const { status, notes } = req.body;

  const order = await Order.findById(req.params.id);
  if (!order) {
    return next(new ErrorResponse(`Order not found with id of ${req.params.id}`, 404));
  }

  // Check if the status transition is valid
  const validStatuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled'];
  if (!validStatuses.includes(status)) {
    return next(new ErrorResponse(`Invalid status: ${status}`, 400));
  }
  
  // Check if order requires prescription verification
  if (order.prescription.required && order.prescription.status !== 'approved' && 
      ['processing', 'shipped', 'delivered'].includes(status)) {
    return next(new ErrorResponse('Cannot process order with unapproved prescription', 400));
  }

  // Update order status
  order.status = status;
  
  // Add status history
  order.statusHistory.push({
    status,
    changedBy: req.user.id,
    notes: notes || `Status changed to ${status}`,
    timestamp: Date.now()
  });

  await order.save();

  // Send notification to user
  await Notification.create({
    user: order.user,
    title: `Order ${status}`,
    message: `Your order #${order.orderNumber} has been ${status}.`,
    type: 'order_update',
    referenceId: order._id
  });

  res.status(200).json({
    success: true,
    data: order
  });
});

// @desc    Delete order
// @route   DELETE /api/v1/orders/:id
// @access  Private/Admin
exports.deleteOrder = asyncHandler(async (req, res, next) => {
  const order = await Order.findById(req.params.id);

  if (!order) {
    return next(
      new ErrorResponse(`Order not found with id of ${req.params.id}`, 404)
    );
  }

  await order.remove();

  res.status(200).json({ success: true, data: {} });
});

/**
 * @desc    Get orders by store
 * @route   GET /api/v1/orders/store/:storeId
 * @access  Private (store, store_manager, admin, superadmin)
 */
exports.getOrdersByStore = asyncHandler(async (req, res, next) => {
  const { storeId } = req.params;
  const { page = 1, limit = 10, status, search, sort = '-createdAt', startDate, endDate } = req.query;
  
  // Validate store ID
  if (!mongoose.Types.ObjectId.isValid(storeId)) {
    return next(new ErrorResponse('Invalid store ID', 400));
  }

  // Check if user has access to this store
  if (req.user.role === 'store' && req.user.store.toString() !== storeId) {
    return next(new ErrorResponse('Not authorized to access orders for this store', 403));
  }

  // Build query
  const query = { store: storeId };
  
  // Filter by status if provided
  if (status) {
    query.status = status;
  }

  // Date range filter
  if (startDate || endDate) {
    query.createdAt = {};
    if (startDate) {
      query.createdAt.$gte = new Date(startDate);
    }
    if (endDate) {
      query.createdAt.$lte = new Date(endDate);
    }
  }

  // Search in order number, customer name, or phone
  if (search) {
    query.$or = [
      { orderNumber: { $regex: search, $options: 'i' } },
      { 'address.name': { $regex: search, $options: 'i' } },
      { 'address.contactNumber': { $regex: search, $options: 'i' } }
    ];
  }

  // Execute query with pagination
  const [orders, total] = await Promise.all([
    Order.find(query)
      .populate('userId', 'name email phone')
      .populate('items.item', 'name price')
      .sort(sort)
      .limit(Number(limit))
      .skip((page - 1) * limit)
      .lean(),
    Order.countDocuments(query)
  ]);

  // Calculate pagination
  const totalPages = Math.ceil(total / limit);
  const hasMore = page < totalPages;

  res.status(200).json({
    success: true,
    count: orders.length,
    total,
    totalPages,
    currentPage: Number(page),
    hasMore,
    data: orders
  });
});
