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

// Get all FAQs (public - active only)
const getAllFAQs = async (req, res) => {
  try {
    const [rows] = await pool.execute(
      `SELECT id, question, answer, display_order
       FROM faqs
       WHERE status = 'active'
       ORDER BY display_order ASC, created_at DESC`
    );
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('Error fetching FAQs:', error);
    res.status(500).json({ success: false, message: 'SSS getirilirken hata oluştu' });
  }
};

// Get all FAQs (admin - all statuses)
const getAdminFAQs = async (req, res) => {
  try {
    const { status } = req.query;
    let query = 'SELECT * FROM faqs';
    const params = [];

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

    query += ' ORDER BY display_order ASC, created_at DESC';

    const [rows] = await pool.execute(query, params);
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('Error fetching admin FAQs:', error);
    res.status(500).json({ success: false, message: 'SSS getirilirken hata oluştu' });
  }
};

// Get single FAQ by ID
const getFAQById = async (req, res) => {
  try {
    const { id } = req.params;
    const [rows] = await pool.execute('SELECT * FROM faqs WHERE id = ?', [id]);

    if (rows.length === 0) {
      return res.status(404).json({ success: false, message: 'SSS bulunamadı' });
    }

    res.json({ success: true, data: rows[0] });
  } catch (error) {
    console.error('Error fetching FAQ:', error);
    res.status(500).json({ success: false, message: 'SSS getirilirken hata oluştu' });
  }
};

// Create new FAQ (admin only)
const createFAQ = async (req, res) => {
  try {
    const { question, answer, display_order, status } = req.body;

    // Validation
    if (!question || !answer) {
      return res.status(400).json({
        success: false,
        message: 'Soru ve cevap alanları zorunludur'
      });
    }

    const [result] = await pool.execute(
      `INSERT INTO faqs (question, answer, display_order, status)
       VALUES (?, ?, ?, ?)`,
      [
        question,
        answer,
        display_order || 0,
        status || 'active'
      ]
    );

    res.status(201).json({
      success: true,
      message: 'SSS başarıyla oluşturuldu',
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error('Error creating FAQ:', error);
    res.status(500).json({ success: false, message: 'SSS oluşturulurken hata oluştu' });
  }
};

// Update FAQ (admin only)
const updateFAQ = async (req, res) => {
  try {
    const { id } = req.params;
    const { question, answer, display_order, status } = req.body;

    // Check if FAQ exists
    const [existing] = await pool.execute('SELECT id FROM faqs WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({ success: false, message: 'SSS bulunamadı' });
    }

    // Validation
    if (!question || !answer) {
      return res.status(400).json({
        success: false,
        message: 'Soru ve cevap alanları zorunludur'
      });
    }

    await pool.execute(
      `UPDATE faqs
       SET question = ?, answer = ?, display_order = ?, status = ?
       WHERE id = ?`,
      [question, answer, display_order, status, id]
    );

    res.json({ success: true, message: 'SSS başarıyla güncellendi' });
  } catch (error) {
    console.error('Error updating FAQ:', error);
    res.status(500).json({ success: false, message: 'SSS güncellenirken hata oluştu' });
  }
};

// Delete FAQ (admin only)
const deleteFAQ = async (req, res) => {
  try {
    const { id } = req.params;

    // Check if FAQ exists
    const [existing] = await pool.execute('SELECT id FROM faqs WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({ success: false, message: 'SSS bulunamadı' });
    }

    await pool.execute('DELETE FROM faqs WHERE id = ?', [id]);
    res.json({ success: true, message: 'SSS başarıyla silindi' });
  } catch (error) {
    console.error('Error deleting FAQ:', error);
    res.status(500).json({ success: false, message: 'SSS silinirken hata oluştu' });
  }
};

module.exports = {
  getAllFAQs,
  getAdminFAQs,
  getFAQById,
  createFAQ,
  updateFAQ,
  deleteFAQ
};
