const mongoose = require('mongoose');

const teacherPaymentSchema = new mongoose.Schema({
  teacherId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Teacher',
    required: true
  },
  teacherDetails: {
    firstName: String,
    lastName: String,
    teacherId: String,
    department: String,
    subject: String,
    email: String,
    phone: String,
    salary: Number
  },
  teacherName: {
    type: String,
    required: true
  },
  employeeId: {
    type: String,
    required: true
  },
  department: {
    type: String,
    required: true
  },
  amount: {
    type: Number,
    required: true,
    min: 0
  },
  paymentMethod: {
    type: String,
    enum: ['Cash', 'Card', 'Bank Transfer'],
    default: 'Cash'
  },
  date: {
    type: Date,
    required: true,
    default: Date.now
  },
  month: {
    type: String,
    required: true,
    enum: [
      'January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'
    ]
  },
  message: {
    type: String,
    required: true
  },
  status: {
    type: String,
    enum: ['Pending', 'Completed', 'Failed'],
    default: 'Completed'
  },
  transactionId: {
    type: String,
    unique: true
  },
  smsSent: {
    type: Boolean,
    default: false
  },
  smsSentAt: Date,
  year: {
    type: Number,
    default: () => new Date().getFullYear()
  }
}, {
  timestamps: true
});

// Generate transaction ID before saving
teacherPaymentSchema.pre('save', async function(next) {
  if (!this.transactionId) {
    const count = await mongoose.model('TeacherPayment').countDocuments();
    this.transactionId = `TCHTXN${Date.now()}${count + 1}`;
  }
  
  // Set year from date
  if (this.date) {
    this.year = new Date(this.date).getFullYear();
  }
  
  next();
});

// Index for better query performance
teacherPaymentSchema.index({ teacherId: 1, month: 1, year: 1 });
teacherPaymentSchema.index({ date: 1 });
teacherPaymentSchema.index({ employeeId: 1 });
teacherPaymentSchema.index({ department: 1 });
teacherPaymentSchema.index({ transactionId: 1 });

// Static method to get payments with filters
teacherPaymentSchema.statics.getPayments = async function(filters = {}, page = 1, limit = 10) {
  const query = {};
  
  if (filters.search) {
    query.$or = [
      { teacherName: { $regex: filters.search, $options: 'i' } },
      { employeeId: { $regex: filters.search, $options: 'i' } },
      { 'teacherDetails.teacherId': { $regex: filters.search, $options: 'i' } },
      { transactionId: { $regex: filters.search, $options: 'i' } }
    ];
  }

  if (filters.department && filters.department !== 'All') {
    query.department = filters.department;
  }

  if (filters.month && filters.month !== 'All') {
    query.month = filters.month;
  }

  if (filters.status && filters.status !== 'All') {
    query.status = filters.status;
  }

  if (filters.paymentMethod && filters.paymentMethod !== 'All') {
    query.paymentMethod = filters.paymentMethod;
  }

  if (filters.startDate || filters.endDate) {
    query.date = {};
    if (filters.startDate) {
      query.date.$gte = new Date(filters.startDate);
    }
    if (filters.endDate) {
      query.date.$lte = new Date(filters.endDate);
    }
  }

  const payments = await this.find(query)
    .populate('teacherId', 'firstName lastName teacherId email phone department subject salary photo')
    .sort({ date: -1, createdAt: -1 })
    .limit(limit * 1)
    .skip((page - 1) * limit);

  const total = await this.countDocuments(query);

  return {
    payments,
    total,
    totalPages: Math.ceil(total / limit),
    currentPage: page
  };
};

const TeacherPayment = mongoose.model('TeacherPayment', teacherPaymentSchema);

module.exports = TeacherPayment;