import pool from '../config/db.js';

export const getAll = async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM categories ORDER BY sort_order ASC');
    res.json(rows);
  } catch (err) {
    console.error('Error in getAll:', err);
    res.status(500).json({ message: err.message });
  }
};

export const getOne = async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM categories WHERE id = ? OR slug = ?', [req.params.id, req.params.id]);
    if (rows.length === 0) return res.status(404).json({ message: 'Category not found' });
    res.json(rows[0]);
  } catch (err) {
    console.error('Error in getOne:', err);
    res.status(500).json({ message: err.message });
  }
};

export const create = async (req, res) => {
  try {
    const { slug, title, subtitle, items, hero_image, sort_order } = req.body;
    
    console.log('Create request body:', req.body); // DEBUG LOG
    
    const finalSlug = slug || title?.toLowerCase().replace(/\s+/g, '-') || `category-${Date.now()}`;
    
    const [result] = await pool.query(
      'INSERT INTO categories (slug, title, subtitle, items, hero_image, sort_order) VALUES (?, ?, ?, ?, ?, ?)',
      [finalSlug, title, subtitle || '', items || '', hero_image || null, sort_order || 0]
    );
    
    const [rows] = await pool.query('SELECT * FROM categories WHERE id = ?', [result.insertId]);
    res.status(201).json(rows[0]);
  } catch (err) {
    console.error('Error in create:', err);
    res.status(500).json({ message: err.message });
  }
};

export const update = async (req, res) => {
  try {
    console.log('=== UPDATE CATEGORY DEBUG ===');
    console.log('Request params:', req.params);
    console.log('Request body:', req.body);
    
    const { slug, title, subtitle, items, hero_image, sort_order } = req.body;
    const { id } = req.params;
    
    console.log('Extracted values:', { slug, title, subtitle, items, hero_image, sort_order, id });
    
    const finalSlug = slug || title?.toLowerCase().replace(/\s+/g, '-') || `category-${id}`;
    
    console.log('Final slug:', finalSlug);
    
    const [result] = await pool.query(
      'UPDATE categories SET slug = ?, title = ?, subtitle = ?, items = ?, hero_image = ?, sort_order = ? WHERE id = ?',
      [finalSlug, title, subtitle || '', items || '', hero_image || null, sort_order || 0, id]
    );
    
    console.log('Update result:', result);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: 'Category not found' });
    }
    
    const [rows] = await pool.query('SELECT * FROM categories WHERE id = ?', [id]);
    console.log('Updated row:', rows[0]);
    res.json(rows[0]);
  } catch (err) {
    console.error('Error in update:', err);
    res.status(500).json({ message: err.message });
  }
};

export const remove = async (req, res) => {
  try {
    const [result] = await pool.query('DELETE FROM categories WHERE id = ?', [req.params.id]);
    if (result.affectedRows === 0) return res.status(404).json({ message: 'Category not found' });
    res.json({ message: 'Category deleted successfully' });
  } catch (err) {
    console.error('Error in remove:', err);
    res.status(500).json({ message: err.message });
  }
};