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

exports.getAllCategories = async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM categories');
        res.json(rows);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.getCategoryById = async (req, res) => {
    const categoryId = req.params.id;

    try {
        const [rows] = await db.query('SELECT * FROM categories WHERE id = ?', [categoryId]);

        if (rows.length === 0) {
            return res.status(404).json({ error: 'Category not found' });
        }

        res.json(rows[0]);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.createCategory = async (req, res) => {
    try {
        const { name } = req.body;
        const [result] = await db.query('INSERT INTO categories (name) VALUES (?)', [name]);
        res.json({ id: result.insertId, name });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.updateCategory = async (req, res) => {
    try {
        const { name } = req.body;
        await metaModel.updateCategory(req.params.id, name);
        res.json({ success: true });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.deleteCategory = async (req, res) => {
    const categoryId = req.params.id;

    try {
        const [result] = await db.query('DELETE FROM categories WHERE id = ?', [categoryId]);

        if (result.affectedRows === 0) {
            return res.status(404).json({ error: 'Category not found or already deleted' });
        }

        res.json({ message: 'Category deleted successfully' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.updateBrand = async (req, res) => {
    try {
        const { name } = req.body;
        await metaModel.updateBrand(req.params.id, name);
        res.json({ success: true });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.getAllBrands = async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM brands');
        res.json(rows);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.getBrandById = async (req, res) => {
    const brandId = req.params.id;

    try {
        const [rows] = await db.query('SELECT * FROM brands WHERE id = ?', [brandId]);

        if (rows.length === 0) {
            return res.status(404).json({ error: 'Brand not found' });
        }

        res.json(rows[0]);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.deleteBrand = async (req, res) => {
    const brandId = req.params.id;

    try {
        const [result] = await db.query('DELETE FROM brands WHERE id = ?', [brandId]);

        if (result.affectedRows === 0) {
            return res.status(404).json({ error: 'Brand not found or already deleted' });
        }

        res.json({ message: 'Brand deleted successfully' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.createBrand = async (req, res) => {
    try {
        const { name } = req.body;
        const [result] = await db.query('INSERT INTO brands (name) VALUES (?)', [name]);
        res.json({ id: result.insertId, name });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.getUnits = async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM units ORDER BY name');
        res.json(rows);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.createUnit = async (req, res) => {
    try {
        const { name } = req.body;
        if (!name) return res.status(400).json({ error: 'Name is required' });

        const [existing] = await db.query('SELECT id FROM units WHERE name = ?', [name.trim()]);
        if (existing.length > 0) {
            return res.status(409).json({ error: 'Unit already exists' });
        }

        const [result] = await db.query('INSERT INTO units (name) VALUES (?)', [name.trim()]);
        res.status(201).json({ id: result.insertId, name });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.updateUnit = async (req, res) => {
    try {
        const { name } = req.body;
        await metaModel.updateUnit(req.params.id, name);
        res.json({ success: true });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.getUnitById = async (req, res) => {
    const brandId = req.params.id;

    try {
        const [rows] = await db.query('SELECT * FROM units WHERE id = ?', [brandId]);

        if (rows.length === 0) {
            return res.status(404).json({ error: 'Unit not found' });
        }

        res.json(rows[0]);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.deleteUnit = async (req, res) => {
    const unitId = req.params.id;

    try {
        const [result] = await db.query('DELETE FROM units WHERE id = ?', [unitId]);

        if (result.affectedRows === 0) {
            return res.status(404).json({ error: 'Unit not found or already deleted' });
        }

        res.json({ message: 'Unit deleted successfully' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.getLatestSku = async (req, res) => {
    try {
      const [rows] = await db.query(
        "SELECT sku FROM items WHERE sku LIKE 'INV%' ORDER BY id DESC LIMIT 1"
      );
  
      let newSku = 'INV0001';
  
      if (rows.length > 0) {
        const latestSku = rows[0].sku;
        const num = parseInt(latestSku.replace('INV', ''), 10) + 1;
        newSku = 'INV' + String(num).padStart(4, '0');
      }
  
      res.json({ sku: newSku });  // ✅ This line matters
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  };

  // ✅ Get all predefined sizes
exports.getSizes = async (req, res) => {
  try {
    const [rows] = await db.query('SELECT id, name FROM sizes ORDER BY name');
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch sizes' });
  }
};

// ✅ Add a new size
exports.createSize = async (req, res) => {
  const { name } = req.body;
  try {
    await db.query('INSERT INTO sizes (name) VALUES (?)', [name]);
    res.status(201).json({ message: 'Size created successfully' });
  } catch (err) {
    res.status(500).json({ error: 'Failed to create size' });
  }
};

exports.updateSize = async (req, res) => {
    try {
        const { name } = req.body;
        await metaModel.updateSize(req.params.id, name);
        res.json({ success: true });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.getSizeById = async (req, res) => {
    const brandId = req.params.id;

    try {
        const [rows] = await db.query('SELECT * FROM sizes WHERE id = ?', [brandId]);

        if (rows.length === 0) {
            return res.status(404).json({ error: 'Size not found' });
        }

        res.json(rows[0]);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
exports.deleteSize = async (req, res) => {
    const unitId = req.params.id;

    try {
        const [result] = await db.query('DELETE FROM sizes WHERE id = ?', [unitId]);

        if (result.affectedRows === 0) {
            return res.status(404).json({ error: 'Size not found or already deleted' });
        }

        res.json({ message: 'Size deleted successfully' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};