const mongoose = require('mongoose');

const examFeeSchema = new mongoose.Schema({
  // Student Information
  studentId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student',
    required: true
  },
  studentName: {
    type: String,
    required: true
  },
  className: {
    type: String,
    required: true
  },
  rollNo: {
    type: String
  },
  
  // Exam Information
  examName: {
    type: String,
    required: true,
    enum: ['Half Yearly', 'Final', 'Monthly Test', 'Quarterly', 'Pre-Test', 'Test Exam']
  },
  examYear: {
    type: Number,
    default: () => new Date().getFullYear()
  },
  
  // Fee Details
  amount: {
    type: Number,
    required: true
  },
  paidAmount: {
    type: Number,
    default: 0
  },
  // Payment Status
  paymentStatus: {
    type: String,
    enum: ['Paid', 'Partial', 'Unpaid'],
    default: 'Unpaid'
  },
  
  // Payment Details
  paymentMethod: {
    type: String,
    enum: ['Cash', 'Bank', 'Mobile Banking', 'Check']
  },
  paymentDate: {
    type: Date
  },
  transactionId: {
    type: String
  },
  
  
  // Receipt
  receiptNo: {
    type: String
  },
  
  // Notes
  remarks: {
    type: String
  },
  
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, {
  timestamps: true
});

// Update due amount and status before saving
examFeeSchema.pre('save', function(next) {
  this.dueAmount = this.amount - this.paidAmount;
  
  if (this.dueAmount <= 0) {
    this.paymentStatus = 'Paid';
  } else if (this.paidAmount > 0) {
    this.paymentStatus = 'Partial';
  } else {
    this.paymentStatus = 'Unpaid';
  }
  
  // Generate simple receipt number
  if (this.paymentStatus === 'Paid' && !this.receiptNo) {
    this.receiptNo = 'RCT-' + Date.now();
  }
  
  next();
});

module.exports = mongoose.model('ExamFee', examFeeSchema);