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

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

// Get all testimonials (admin - all statuses)
const getAdminTestimonials = async (req, res) => {
  try {
    const { status } = req.query;
    let query = 'SELECT * FROM testimonials';
    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 testimonials:', error);
    res.status(500).json({ success: false, message: 'Yorumlar getirilirken hata oluştu' });
  }
};

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

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

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

// Create new testimonial (admin only)
const createTestimonial = async (req, res) => {
  try {
    const { customer_name, comment, source, source_url, review_date, display_order, status } = req.body;

    // Validation
    if (!customer_name || !comment) {
      return res.status(400).json({
        success: false,
        message: 'Müşteri adı ve yorum alanları zorunludur'
      });
    }

    const [result] = await pool.execute(
      `INSERT INTO testimonials (customer_name, comment, source, source_url, review_date, display_order, status)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [
        customer_name,
        comment,
        source || 'website',
        source_url || null,
        review_date || null,
        display_order || 0,
        status || 'active'
      ]
    );

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

// Update testimonial (admin only)
const updateTestimonial = async (req, res) => {
  try {
    const { id } = req.params;
    const { customer_name, comment, source, source_url, review_date, display_order, status } = req.body;

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

    // Validation
    if (!customer_name || !comment) {
      return res.status(400).json({
        success: false,
        message: 'Müşteri adı ve yorum alanları zorunludur'
      });
    }

    await pool.execute(
      `UPDATE testimonials
       SET customer_name = ?, comment = ?, source = ?, source_url = ?,
           review_date = ?, display_order = ?, status = ?
       WHERE id = ?`,
      [customer_name, comment, source, source_url, review_date, display_order, status, id]
    );

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

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

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

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

module.exports = {
  getAllTestimonials,
  getAdminTestimonials,
  getTestimonialById,
  createTestimonial,
  updateTestimonial,
  deleteTestimonial
};
