// ============================================
// REGISTER CONTROLLER
// controllers/registerController.js
// ============================================
const { Store,Transaction, Register, User, RegisterAssignment } = require('../models');


const { Op } = require('sequelize');

const { Sequelize } = require('sequelize');   // add this import

// ADD THIS LINE

// Get all registers for a store
exports.getStoreRegisters = async (req, res) => {
  try {
    const { storeId } = req.params;

    // Verify store exists
    const store = await Store.findByPk(storeId);
    if (!store) {
      return res.status(404).json({
        success: false,
        message: 'Store not found'
      });
    }

    const registers = await Register.findAll({
      where: { storeId },
      include: [
        {
          model: User,
          as: 'openedUser',
          attributes: ['id', 'lastName', 'firstName']
        },
        {
          model: User,
          as: 'closedUser',
          attributes: ['id', 'lastName', 'firstName']
        },
        {
          model: User,
          as: 'assignedUsers',
          attributes: ['id', 'firstName', 'lastName', 'email'],
          through: { 
            attributes: ['isPrimary', 'assignedAt'],
            where: { isActive: true }
          },
          required: false
        }
      ],
      order: [['createdAt', 'ASC']]
    });

    res.json({
      success: true,
      registers
    });
  } catch (error) {
    console.error('Error fetching registers:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch registers',
      error: error.message
    });
  }
};



exports.getAllRegisters = async (req, res) => {
  console.log("🔥 INCOMING REQUEST TO GET /registers");
  console.log("🔍 QUERY PARAMS:", req.query);

  try {
    console.log("🚀 CONTROLLER REACHED SUCCESSFULLY");

    const registers = await Register.findAll({
      include: [
        {
          model: User,
          as: 'openedUser',
          attributes: ['id', 'lastName', 'firstName']
        },
        {
          model: User,
          as: 'closedUser',
          attributes: ['id', 'lastName', 'firstName']
        },
        {
          model: Store,
          as: 'store',
          attributes: ['id', 'name', 'code', 'address']
        },
        {
          model: User,
          as: 'assignedUsers',
          attributes: ['id', 'firstName', 'lastName', 'email'],
          through: {
            attributes: ['isPrimary', 'assignedAt'],
            where: { isActive: true }
          },
          required: false
        }
      ],
      order: [['createdAt', 'ASC']]
    });

    console.log(`✅ SUCCESS: LOADED ${registers.length} REGISTERS`);

    return res.json({
      success: true,
      registers
    });

  } catch (error) {
    console.error("❌ ERROR IN getAllRegisters");
    console.error("🟥 ERROR NAME:", (error.name || "UNKNOWN").toUpperCase());
    console.error("🟥 ERROR MESSAGE:", (error.message || "").toUpperCase());
    console.error("🟥 ERROR STACK:", error.stack);

    // Sequelize Association Errors
    if (error.name === "SequelizeEagerLoadingError") {
      return res.status(400).json({
        success: false,
        message: "INVALID ASSOCIATION IN REGISTER MODEL",
        error: error.message.toUpperCase(),
      });
    }

    // Sequelize Validation Errors
    if (error.name === "SequelizeValidationError") {
      return res.status(400).json({
        success: false,
        message: "VALIDATION ERROR",
        errors: error.errors,
      });
    }

    // Sequelize Database Errors
    if (error.name === "SequelizeDatabaseError") {
      return res.status(400).json({
        success: false,
        message: "DATABASE ERROR",
        error: error.message.toUpperCase(),
      });
    }

    // Fallback
    return res.status(500).json({
      success: false,
      message: "SERVER ERROR WHILE FETCHING REGISTERS",
      error: error.message.toUpperCase(),
    });
  }
};


// Get single register
exports.getRegisterById = async (req, res) => {
  try {
    const { id } = req.params;

    const register = await Register.findByPk(id, {
      include: [
        {
          model: Store,
          as: 'store',
          attributes: ['id', 'name', 'code']
        },
        {
          model: User,
          as: 'openedUser',
          attributes: ['id', 'firstName', 'lastName']
        },
        {
          model: User,
          as: 'closedUser',
          attributes: ['id', 'firstName', 'lastName']
        },
        {
          model: RegisterAssignment,
          as: 'assignments',
          where: { isActive: true },
          required: false,
          include: [
            {
              model: User,
              as: 'user',
              attributes: ['id', 'firstName', 'lastName', 'email']
            },
            {
              model: User,
              as: 'assignedByUser',
              attributes: ['id', 'firstName', 'lastName']
            }
          ]
        }
      ]
    });

    if (!register) {
      return res.status(404).json({
        success: false,
        message: 'Register not found'
      });
    }

    res.json({
      success: true,
      register
    });
  } catch (error) {
    console.error('Error fetching register:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch register',
      error: error.message
    });
  }
};

// Create new register
exports.createRegister = async (req, res) => {
  try {
    const { name, storeId, openingCash = 0, notes, code } = req.body;

    // Validation
    if (!name || !storeId) {
      return res.status(400).json({
        success: false,
        message: 'Name and store ID are required'
      });
    }

    // Verify store exists and is active
    const store = await Store.findByPk(storeId);
    if (!store) {
      return res.status(404).json({
        success: false,
        message: 'Store not found'
      });
    }

    if (!store.isActive) {
      return res.status(400).json({
        success: false,
        message: 'Cannot add register to inactive store'
      });
    }

    const register = await Register.create({
      name,
      code,
      storeId,
      openingCash: parseFloat(openingCash) || 0,
      currentCash: 0,
      isOpen: false,
      status: 'inactive',
      isActive: true,
      notes
    });

    res.status(201).json({
      success: true,
      message: 'Register created successfully',
      register
    });
  } catch (error) {
    console.error('Error creating register:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to create register',
      error: error.message
    });
  }
};

// Update register
exports.updateRegister = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, code, openingCash, notes,storeId, isActive } = req.body;

    const register = await Register.findByPk(id);

    if (!register) {
      return res.status(404).json({
        success: false,
        message: 'Register not found'
      });
    }

    // Don't allow updates to open registers except notes
    if (register.isOpen && (name || code || openingCash !== undefined)) {
      return res.status(400).json({
        success: false,
        message: 'Cannot update name, code, or opening cash of an open register'
      });
    }

    await register.update({
      name: name || register.name,
      code: code || register.code,
      storeId: storeId || register.storeId,
      openingCash: openingCash !== undefined ? parseFloat(openingCash) : register.openingCash,
      notes: notes !== undefined ? notes : register.notes,
      isActive: isActive !== undefined ? isActive : register.isActive
    });

    res.json({
      success: true,
      message: 'Register updated successfully',
      register
    });
  } catch (error) {
    console.error('Error updating register:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to update register',
      error: error.message
    });
  }
};

// Open register (start shift)
// exports.openRegister = async (req, res) => {
//   try {
//     const { id } = req.params;
//     const { openingCash, openedBy } = req.body;
//     const userId = openedBy || req.user?.id;

//     const register = await Register.findByPk(id, {
//       include: [
//         { model: Store, as: 'store' },
//         {
//           model: RegisterAssignment,
//           as: 'assignments',
//           where: { isActive: true, userId },
//           required: false
//         }
//       ]
//     });

//     if (!register) {
//       return res.status(404).json({
//         success: false,
//         message: 'Register not found'
//       });
//     }

//     // Check if store is active
//     if (!register.store.isActive) {
//       return res.status(400).json({
//         success: false,
//         message: 'Cannot open register in inactive store'
//       });
//     }

//     // Check if user is assigned to this register
//     if (register.assignments.length === 0) {
//       return res.status(403).json({
//         success: false,
//         message: 'You are not assigned to this register'
//       });
//     }

//     // Check if register is already open
//     if (register.isOpen) {
//       return res.status(400).json({
//         success: false,
//         message: 'Register is already open'
//       });
//     }

//     // Validate opening cash
//     if (openingCash === undefined || openingCash < 0) {
//       return res.status(400).json({
//         success: false,
//         message: 'Valid opening cash amount is required'
//       });
//     }

//     const openingAmount = parseFloat(openingCash);

//     await register.update({
//       status: 'open',
//       isOpen: true,
//       openingCash: openingAmount,
//       currentCash: openingAmount,
//       openedAt: new Date(),
//       openedBy: userId,
//       closedAt: null,
//       closedBy: null
//     });

//     res.json({
//       success: true,
//       message: 'Register opened successfully',
//       register
//     });
//   } catch (error) {
//     console.error('Error opening register:', error);
//     res.status(500).json({
//       success: false,
//       message: 'Failed to open register',
//       error: error.message
//     });
//   }
// };


exports.openRegister = async (req, res) => {
  try {
    const { id } = req.params;
    const { openingCash, openedBy } = req.body;
    const userId = openedBy || req.user?.id;

    const register = await Register.findByPk(id, {
      include: [
        { model: Store, as: 'store' },
        {
          model: RegisterAssignment,
          as: 'assignments',
          where: { isActive: true, userId },
          required: false
        }
      ]
    });

    if (!register) {
      return res.status(404).json({
        success: false,
        message: 'Register not found'
      });
    }

    // Check if store is active
    if (!register.store.isActive) {
      return res.status(400).json({
        success: false,
        message: 'Cannot open register in inactive store'
      });
    }

    // Check if user is assigned to this register
    if (register.assignments.length === 0) {
      return res.status(403).json({
        success: false,
        message: 'You are not assigned to this register'
      });
    }

    // ────────────────────────────────
    // THIS IS THE ONLY CHANGE (added block)
    // ────────────────────────────────
    if (register.isOpen) {
      // If it's already open by the SAME user → allow resume (Continue Shift)
      if (register.openedBy === userId) {
        return res.json({
          success: true,
          message: 'Shift resumed successfully',
          register: register.get({ plain: true }) // clean object for frontend
        });
      }

      // Different user → block
      return res.status(400).json({
        success: false,
        message: 'Register is already open by another cashier'
      });
    }
    // ────────────────────────────────

    // Validate opening cash
    if (openingCash === undefined || openingCash < 0) {
      return res.status(400).json({
        success: false,
        message: 'Valid opening cash amount is required'
      });
    }

    const openingAmount = parseFloat(openingCash);

    await register.update({
      status: 'open',
      isOpen: true,
      openingCash: openingAmount,
      currentCash: openingAmount,
      openedAt: new Date(),
      openedBy: userId,
      closedAt: null,
      closedBy: null
    });

    res.json({
      success: true,
      message: 'Register opened successfully',
      register: register.get({ plain: true })
    });
  } catch (error) {
    console.error('Error opening register:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to open register',
      error: error.message
    });
  }
};

// Close register (end shift)
exports.closeRegister = async (req, res) => {
  try {
    const { id } = req.params;
    const { closingCash, notes, closedBy } = req.body;
    const userId = closedBy || req.user?.id;

    const register = await Register.findByPk(id);

    if (!register) {
      return res.status(404).json({
        success: false,
        message: 'Register not found'
      });
    }

    // Check if register is open
    if (!register.isOpen) {
      return res.status(400).json({
        success: false,
        message: 'Register is not open'
      });
    }

    // Validate closing cash
    if (closingCash === undefined || closingCash < 0) {
      return res.status(400).json({
        success: false,
        message: 'Valid closing cash amount is required'
      });
    }

    const closingAmount = parseFloat(closingCash);
    const expectedCash = register.currentCash;
    const difference = closingAmount - expectedCash;

    await register.update({
      status: 'closed',
      isOpen: false,
      currentCash: closingAmount,
      closedAt: new Date(),
      closedBy: userId,
      notes: notes || register.notes
    });

    // Log cash difference if significant
    if (Math.abs(difference) > 0) {
      console.log(`Cash difference detected for register ${id}: ${difference}`);
    }

    res.json({
      success: true,
      message: 'Register closed successfully',
      register,
      cashDifference: difference,
      expectedCash,
      actualCash: closingAmount
    });
  } catch (error) {
    console.error('Error closing register:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to close register',
      error: error.message
    });
  }
};

// ============================================
// NEW ASSIGNMENT ENDPOINTS
// ============================================

// Assign user to register
exports.assignUserToRegister = async (req, res) => {
  try {
    const { id } = req.params; // registerId
    const { userId, isPrimary = false } = req.body;
    const assignedBy = req.user?.id;

    // Validate inputs
    if (!userId) {
      return res.status(400).json({
        success: false,
        message: 'User ID is required'
      });
    }

    // Check if register exists
    const register = await Register.findByPk(id);
    if (!register) {
      return res.status(404).json({
        success: false,
        message: 'Register not found'
      });
    }

    // Check if user exists
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: 'User not found'
      });
    }

    // Check if assignment already exists
    const existingAssignment = await RegisterAssignment.findOne({
      where: {
        registerId: id,
        userId,
        isActive: true
      }
    });

    if (existingAssignment) {
      return res.status(400).json({
        success: false,
        message: 'User is already assigned to this register'
      });
    }

    // If setting as primary, unset other primary assignments for this register
    if (isPrimary) {
      await RegisterAssignment.update(
        { isPrimary: false },
        {
          where: {
            registerId: id,
            isActive: true,
            isPrimary: true
          }
        }
      );
    }

    // Create assignment
    const assignment = await RegisterAssignment.create({
      registerId: id,
      userId,
      assignedBy,
      isPrimary,
      isActive: true,
      assignedAt: new Date()
    });

    // Fetch the complete assignment with user details
    const completeAssignment = await RegisterAssignment.findByPk(assignment.id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'firstName', 'lastName', 'email']
        },
        {
          model: User,
          as: 'assignedByUser',
          attributes: ['id', 'firstName', 'lastName']
        }
      ]
    });

    res.status(201).json({
      success: true,
      message: 'User assigned to register successfully',
      assignment: completeAssignment
    });
  } catch (error) {
    console.error('Error assigning user to register:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to assign user to register',
      error: error.message
    });
  }
};

// Unassign user from register
exports.unassignUserFromRegister = async (req, res) => {
  try {
    const { id, userId } = req.params;

    const assignment = await RegisterAssignment.findOne({
      where: {
        registerId: id,
        userId,
        isActive: true
      }
    });

    if (!assignment) {
      return res.status(404).json({
        success: false,
        message: 'Assignment not found or already inactive'
      });
    }

    // Soft delete - mark as inactive
    await assignment.update({
      isActive: false,
      unassignedAt: new Date()
    });

    res.json({
      success: true,
      message: 'User unassigned from register successfully'
    });
  } catch (error) {
    console.error('Error unassigning user from register:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to unassign user from register',
      error: error.message
    });
  }
};

// Get all users assigned to a register
exports.getRegisterAssignedUsers = async (req, res) => {
  try {
    const { id } = req.params;

    const register = await Register.findByPk(id);
    if (!register) {
      return res.status(404).json({
        success: false,
        message: 'Register not found'
      });
    }

    const assignments = await RegisterAssignment.findAll({
      where: {
        registerId: id,
        isActive: true
      },
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'firstName', 'lastName', 'email']
        },
        {
          model: User,
          as: 'assignedByUser',
          attributes: ['id', 'firstName', 'lastName']
        }
      ],
      order: [['isPrimary', 'DESC'], ['assignedAt', 'ASC']]
    });

    res.json({
      success: true,
      assignments
    });
  } catch (error) {
    console.error('Error fetching register assignments:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch register assignments',
      error: error.message
    });
  }
};

// Get all registers assigned to a user
// exports.getUserAssignedRegisters = async (req, res) => {
//   try {
//     const { userId } = req.params;

//     const user = await User.findByPk(userId);
//     if (!user) {
//       return res.status(404).json({
//         success: false,
//         message: 'User not found'
//       });
//     }

//     const assignments = await RegisterAssignment.findAll({
//       where: {
//         userId,
//         isActive: true
//       },
//       include: [
//         {
//           model: Register,
//           as: 'register',
//           include: [
//             {
//               model: Store,
//               as: 'store',
//               attributes: ['id', 'name', 'code']
//             }
//           ]
//         }
//       ],
//       order: [['isPrimary', 'DESC'], ['assignedAt', 'ASC']]
//     });

//     res.json({
//       success: true,
//       assignments
//     });
//   } catch (error) {
//     console.error('Error fetching user register assignments:', error);
//     res.status(500).json({
//       success: false,
//       message: 'Failed to fetch user register assignments',
//       error: error.message
//     });
//   }
// };

// GET /registers/:userId/assignments
exports.getUserAssignedRegisters = async (req, res) => {
  try {
    const { userId } = req.params;

    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: 'User not found'
      });
    }

    const assignments = await RegisterAssignment.findAll({
      where: {
        userId
      },
      include: [
        {
          model: Register,
          as: 'register',
          attributes: [
            'id', 'name', 'code', 'isOpen', 'isActive',
             'openedBy', 'openingCash', 'openedAt'
          ],
          include: [
            {
              model: Store,
              as: 'store',
              attributes: ['id', 'name', 'code']
            }
          ]
        }
      ],
      order: [['isPrimary', 'DESC'], ['assignedAt', 'ASC']]
    });

    const registers = assignments.map(a => a.register);

    console.log(`User ${userId} assigned registers:`, registers);

    // Send clean data to frontend
    res.json({
      success: true,
      registers // → each has assignment + register.isOpen, currentUserId, etc.
    });

  } catch (error) {
    console.error('Error fetching user register assignments:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch registers',
      error: error.message
    });
  }
};

// Update assignment (e.g., set as primary)
exports.updateRegisterAssignment = async (req, res) => {
  try {
    const { id, userId } = req.params;
    const { isPrimary } = req.body;

    const assignment = await RegisterAssignment.findOne({
      where: {
        registerId: id,
        userId,
        isActive: true
      }
    });

    if (!assignment) {
      return res.status(404).json({
        success: false,
        message: 'Assignment not found'
      });
    }

    // If setting as primary, unset other primary assignments for this register
    if (isPrimary === true) {
      await RegisterAssignment.update(
        { isPrimary: false },
        {
          where: {
            registerId: id,
            isActive: true,
            isPrimary: true,
            id: { [Op.ne]: assignment.id }
          }
        }
      );
    }

    await assignment.update({ isPrimary });

    res.json({
      success: true,
      message: 'Assignment updated successfully',
      assignment
    });
  } catch (error) {
    console.error('Error updating assignment:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to update assignment',
      error: error.message
    });
  }
};

// Delete register
exports.deleteRegister = async (req, res) => {
  try {
    const { id } = req.params;

    const register = await Register.findByPk(id);

    if (!register) {
      return res.status(404).json({
        success: false,
        message: 'Register not found'
      });
    }

    // Cannot delete open register
    if (register.isOpen) {
      return res.status(400).json({
        success: false,
        message: 'Cannot delete an open register. Please close it first.'
      });
    }

    await register.destroy();

    res.json({
      success: true,
      message: 'Register deleted successfully'
    });
  } catch (error) {
    console.error('Error deleting register:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to delete register',
      error: error.message
    });
  }
};

// Update register cash (for transactions)
exports.updateRegisterCash = async (req, res) => {
  try {
    const { id } = req.params;
    const { amount, type } = req.body; // type: 'add' or 'subtract'

    const register = await Register.findByPk(id);

    if (!register) {
      return res.status(404).json({
        success: false,
        message: 'Register not found'
      });
    }

    if (!register.isOpen) {
      return res.status(400).json({
        success: false,
        message: 'Register must be open to update cash'
      });
    }

    const cashAmount = parseFloat(amount);
    
    if (isNaN(cashAmount) || cashAmount <= 0) {
      return res.status(400).json({
        success: false,
        message: 'Invalid cash amount'
      });
    }

    let newCurrentCash = parseFloat(register.currentCash);

    if (type === 'add') {
      newCurrentCash += cashAmount;
    } else if (type === 'subtract') {
      newCurrentCash -= cashAmount;
    } else {
      return res.status(400).json({
        success: false,
        message: 'Invalid transaction type. Use "add" or "subtract"'
      });
    }

    const previousCash = register.currentCash;
    await register.update({
      currentCash: newCurrentCash
    });

    console.log(`Register ${id} cash ${type}: ${cashAmount}. New balance: ${newCurrentCash}`);

    res.json({
      success: true,
      message: 'Register cash updated successfully',
      previousCash,
      newCash: newCurrentCash,
      amount: cashAmount,
      type
    });
  } catch (error) {
    console.error('Error updating register cash:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to update register cash',
      error: error.message
    });
  }
};

// Get register statistics
exports.getRegisterStats = async (req, res) => {
  try {
    const { id } = req.params;

    const register = await Register.findByPk(id, {
      include: [
        {
          model: Store,
          as: 'store',
          attributes: ['id', 'name', 'code']
        },
        {
          model: User,
          as: 'assignedUsers',
          attributes: ['id', 'firstName', 'lastName'],
          through: {
            attributes: ['isPrimary'],
            where: { isActive: true }
          },
          required: false
        }
      ]
    });

    if (!register) {
      return res.status(404).json({
        success: false,
        message: 'Register not found'
      });
    }

    res.json({
      success: true,
      register
    });
  } catch (error) {
    console.error('Error fetching register stats:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch register statistics',
      error: error.message
    });
  }
};

// GET /registers/sales-summary
exports.getRegisterSalesSummary = async (req, res) => {
  try {
    const { startDate, endDate, storeId } = req.query;

    // Build date filter (inclusive)
    const whereClause = {};
    if (startDate || endDate) {
      whereClause.completedAt = {};
      if (startDate) whereClause.completedAt[Op.gte] = new Date(startDate);
      if (endDate) {
        const end = new Date(endDate);
        end.setHours(23, 59, 59, 999);
        whereClause.completedAt[Op.lte] = end;
      }
    }

    // Only completed transactions
    whereClause.status = 'completed';

    const summary = await Transaction.findAll({
      where: whereClause,
      attributes: [
        'registerId',
        [sequelize.fn('SUM', sequelize.col('totalAmount')), 'totalSales'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'transactionCount']
      ],
      include: [
        {
          model: Register,
          as: 'register',
          attributes: ['id', 'name', 'code'],
          include: [
            {
              model: Store,
              as: 'store',
              attributes: ['id', 'name'],
              where: storeId ? { id: storeId } : undefined,
              required: !!storeId
            }
          ],
          required: true
        }
      ],
      group: ['registerId', 'register.id', 'register->store.id'],
      order: [[sequelize.literal('totalSales'), 'DESC']],
      raw: true,
      nest: true
    });

    // Format response
    const formatted = summary.map(row => ({
      registerId: row.registerId,
      registerName: row.register.name,
      registerCode: row.register.code || `REG-${row.registerId}`,
      storeName: row.register.store?.name || 'Unknown',
      totalSales: parseFloat(row.totalSales || 0),
      transactionCount: parseInt(row.transactionCount || 0)
    }));

    res.json({
      success: true,
      summary: formatted,
      period: { startDate, endDate },
      totalRegisters: formatted.length,
      grandTotal: formatted.reduce((sum, r) => sum + r.totalSales, 0),
      totalTransactions: formatted.reduce((sum, r) => sum + r.transactionCount, 0)
    });

  } catch (error) {
    console.error('Error fetching register sales summary:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch sales summary',
      error: error.message
    });
  }
};


// GET /registers/today-sales-summary
// GET /api/registers/today-sales-summary
exports.getTodaySalesSummary = async (req, res) => {
  try {
    // Start of today at 00:00:00
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    // Start of tomorrow
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    const summary = await Transaction.findAll({
      where: {
        status: 'completed',
        transactionDate: {
          [Op.gte]: today,
          [Op.lt]: tomorrow
        }
      },
      attributes: [
        'registerId',
        [Sequelize.fn('SUM', Sequelize.col('totalAmount')), 'totalSales'],
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'transactionCount']
      ],
      group: ['registerId'],
      raw: true
    });
console.log('Raw summary from DB:', summary); // ← ADD THIS

const salesMap = {};
summary.forEach(row => {
  const id = String(row.registerId);
  salesMap[id] = {
    totalSales: parseFloat(row.totalSales || 0),
    transactionCount: parseInt(row.transactionCount || 0)
  };
  console.log(`Register ${id} → Ksh ${salesMap[id].totalSales}`); // ← SEE THIS IN TERMINAL
});

console.log('Final salesMap sent:', salesMap); // ← THIS MUST SHOW DATA

res.json({
  success: true,
  salesByRegister: salesMap
});

  } catch (error) {
    console.error('Error fetching today sales:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to load sales summary',
      error: error.message
    });
  }
};