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

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

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

    query += ' ORDER BY display_order ASC, name ASC';

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

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

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

  static async checkSlugExists(slug, excludeId = null) {
    let query = 'SELECT COUNT(*) as count FROM page_categories WHERE slug = ?';
    const params = [slug];

    if (excludeId) {
      query += ' AND id != ?';
      params.push(excludeId);
    }

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

  static async create(data) {
    const { name, slug, description, status, display_order } = data;

    // Check if slug already exists
    const slugExists = await this.checkSlugExists(slug);
    if (slugExists) {
      throw new Error('Bu slug zaten kullanılıyor. Lütfen farklı bir slug girin.');
    }

    const [result] = await db.query(
      'INSERT INTO page_categories (name, slug, description, status, display_order) VALUES (?, ?, ?, ?, ?)',
      [name, slug, description || null, status || 'active', display_order || 0]
    );

    return result.insertId;
  }

  static async update(id, data) {
    const { name, slug, description, status, display_order } = data;

    // Check if slug already exists (excluding current category)
    const slugExists = await this.checkSlugExists(slug, id);
    if (slugExists) {
      throw new Error('Bu slug zaten kullanılıyor. Lütfen farklı bir slug girin.');
    }

    const [result] = await db.query(
      'UPDATE page_categories SET name = ?, slug = ?, description = ?, status = ?, display_order = ? WHERE id = ?',
      [name, slug, description, status, display_order, id]
    );

    return result.affectedRows > 0;
  }

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

module.exports = PageCategory;
