import { executeQuery } from '../config/database.js';

export class PaymentItem {
  constructor(data) {
    this.id = data.id;
    this.payment_item_id = data.payment_item_id;
    this.payment_item = data.payment_item;
    this.amount = data.amount;
    this.service_type_id = data.service_type_id;
    this.description = data.description;
    this.is_active = data.is_active;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  // Get all active payment items
  static async getAllActive() {
    const query = `
      SELECT * FROM payment_items 
      WHERE is_active = TRUE 
      ORDER BY payment_item ASC
    `;
    const rows = await executeQuery(query);
    return rows.map(row => new PaymentItem(row));
  }

  // Get payment item by ID
  static async getById(paymentItemId) {
    const query = `
      SELECT * FROM payment_items 
      WHERE payment_item_id = ? AND is_active = TRUE
    `;
    const rows = await executeQuery(query, [paymentItemId]);
    return rows.length > 0 ? new PaymentItem(rows[0]) : null;
  }

  // Create new payment item
  static async create(data) {
    const query = `
      INSERT INTO payment_items 
      (payment_item_id, payment_item, amount, service_type_id, description) 
      VALUES (?, ?, ?, ?, ?)
    `;
    const result = await executeQuery(query, [
      data.payment_item_id,
      data.payment_item,
      data.amount,
      data.service_type_id,
      data.description
    ]);
    return result.insertId;
  }

  // Update payment item
  static async update(paymentItemId, data) {
    const query = `
      UPDATE payment_items 
      SET payment_item = ?, amount = ?, service_type_id = ?, description = ?, updated_at = CURRENT_TIMESTAMP
      WHERE payment_item_id = ?
    `;
    await executeQuery(query, [
      data.payment_item,
      data.amount,
      data.service_type_id,
      data.description,
      paymentItemId
    ]);
  }

  // Deactivate payment item
  static async deactivate(paymentItemId) {
    const query = `
      UPDATE payment_items 
      SET is_active = FALSE, updated_at = CURRENT_TIMESTAMP
      WHERE payment_item_id = ?
    `;
    await executeQuery(query, [paymentItemId]);
  }

  // Get all payment items (including inactive) - for admin
  static async getAll() {
    const query = `
      SELECT * FROM payment_items 
      ORDER BY is_active DESC, payment_item ASC
    `;
    const rows = await executeQuery(query);
    return rows.map(row => new PaymentItem(row));
  }
}
