const db = require('../config/database');

class ContactMessage {
  static async getAll(filters = {}) {
    let query = 'SELECT * FROM contact_messages WHERE 1=1';
    const params = [];

    if (filters.status) {
      query += ' AND status = ?';
      params.push(filters.status);
    }

    query += ' ORDER BY created_at DESC';

    const [rows] = await db.query(query, params);
    return rows;
  }

  static async getById(id) {
    const [rows] = await db.query('SELECT * FROM contact_messages WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async create(data) {
    const { name, email, phone, subject, message } = data;

    const [result] = await db.query(
      `INSERT INTO contact_messages (name, email, phone, subject, message, status)
       VALUES (?, ?, ?, ?, ?, 'new')`,
      [name, email, phone || null, subject || null, message]
    );

    return result.insertId;
  }

  static async updateStatus(id, status) {
    const [result] = await db.query(
      'UPDATE contact_messages SET status = ? WHERE id = ?',
      [status, id]
    );
    return result.affectedRows > 0;
  }

  static async delete(id) {
    const [result] = await db.query('DELETE FROM contact_messages WHERE id = ?', [id]);
    return result.affectedRows > 0;
  }

  static async getUnreadCount() {
    const [rows] = await db.query(
      "SELECT COUNT(*) as count FROM contact_messages WHERE status = 'new'"
    );
    return rows[0].count;
  }
}

module.exports = ContactMessage;
