const mongoose = require('mongoose');

const paymentSchema = new mongoose.Schema({
  studentId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student',
    required: true
  },
  studentDetails: {
    firstName: String,
    lastName: String,
    roll: String,
    class: String,
    studentId: String,
    admissionId: String,
    phone: String
  },
  studentName: {
    type: String,
    required: true
  },
  roll: {
    type: String,
    required: true
  },
  class: {
    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
}, {
  timestamps: true
});

// Generate transaction ID before saving
paymentSchema.pre('save', async function(next) {
  if (!this.transactionId) {
    const count = await mongoose.model('Payment').countDocuments();
    this.transactionId = `TXN${Date.now()}${count + 1}`;
  }
  next();
});

// Index for better query performance
paymentSchema.index({ studentId: 1, month: 1, year: 1 });
paymentSchema.index({ date: 1 });
paymentSchema.index({ roll: 1 });
paymentSchema.index({ class: 1 });

const Payment = mongoose.model('Payment', paymentSchema);

module.exports = Payment;