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

const Categories = {
  async getAll() {
    const [rows] = await db.query('SELECT * FROM categories ORDER BY sort_order ASC');
    return rows;
  },

  async getBySlug(slug) {
    const [rows] = await db.query('SELECT * FROM categories WHERE slug = ?', [slug]);
    return rows[0] || null;
  },

  async create(data) {
    const { slug, title, subtitle, items, hero_image, sort_order } = data;
    const [result] = await db.query(
      'INSERT INTO categories (slug, title, subtitle, items, hero_image, sort_order) VALUES (?,?,?,?,?,?)',
      [slug, title, subtitle || '', items || '', hero_image || '', sort_order || 0]
    );
    return result.insertId;
  },

  async update(slug, data) {
    const { title, subtitle, items, hero_image, sort_order } = data;
    const [result] = await db.query(
      'UPDATE categories SET title=?, subtitle=?, items=?, hero_image=?, sort_order=? WHERE slug=?',
      [title, subtitle || '', items || '', hero_image || '', sort_order || 0, slug]
    );
    return result.affectedRows;
  },

  async remove(slug) {
    const [result] = await db.query('DELETE FROM categories WHERE slug = ?', [slug]);
    return result.affectedRows;
  },
};

module.exports = Categories;