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

// Check if IP has already given consent today
const checkConsent = async (req, res) => {
  try {
    const ipAddress = req.ip || req.connection.remoteAddress || null;

    if (!ipAddress) {
      return res.json({ success: true, hasConsent: false });
    }

    // Check if this IP has given consent TODAY
    const [rows] = await pool.execute(
      'SELECT id, consent_type, created_at FROM cookie_consent_logs WHERE ip_address = ? AND DATE(created_at) = CURDATE() ORDER BY created_at DESC LIMIT 1',
      [ipAddress]
    );

    if (rows.length > 0) {
      return res.json({
        success: true,
        hasConsent: true,
        consentType: rows[0].consent_type,
        consentDate: rows[0].created_at
      });
    }

    res.json({ success: true, hasConsent: false });
  } catch (error) {
    console.error('Error checking cookie consent:', error);
    res.status(500).json({
      success: false,
      message: 'Çerez izni kontrolü sırasında hata oluştu'
    });
  }
};

// Save cookie consent
const saveConsent = async (req, res) => {
  try {
    const { consentType } = req.body;

    // Validation
    if (!consentType || !['accepted', 'rejected'].includes(consentType)) {
      return res.status(400).json({
        success: false,
        message: 'Geçerli bir onay tipi belirtmelisiniz (accepted/rejected)'
      });
    }

    const ipAddress = req.ip || req.connection.remoteAddress || null;
    const userAgent = req.get('User-Agent') || null;

    if (!ipAddress) {
      return res.status(400).json({
        success: false,
        message: 'IP adresi alınamadı'
      });
    }

    // Save consent
    await pool.execute(
      'INSERT INTO cookie_consent_logs (ip_address, user_agent, consent_type) VALUES (?, ?, ?)',
      [ipAddress, userAgent, consentType]
    );

    res.json({
      success: true,
      message: 'Çerez tercihiniz kaydedildi'
    });
  } catch (error) {
    console.error('Error saving cookie consent:', error);
    res.status(500).json({
      success: false,
      message: 'Çerez izni kaydedilirken hata oluştu'
    });
  }
};

// Get all consent logs (admin only)
const getAllConsents = async (req, res) => {
  try {
    const { consentType, startDate, endDate } = req.query;
    let query = 'SELECT * FROM cookie_consent_logs WHERE 1=1';
    const params = [];

    if (consentType) {
      query += ' AND consent_type = ?';
      params.push(consentType);
    }

    if (startDate) {
      query += ' AND DATE(created_at) >= ?';
      params.push(startDate);
    }

    if (endDate) {
      query += ' AND DATE(created_at) <= ?';
      params.push(endDate);
    }

    query += ' ORDER BY created_at DESC LIMIT 1000';

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

// Get consent statistics (admin only)
const getStats = async (req, res) => {
  try {
    const [stats] = await pool.execute(`
      SELECT
        COUNT(*) as total,
        SUM(CASE WHEN consent_type = 'accepted' THEN 1 ELSE 0 END) as accepted,
        SUM(CASE WHEN consent_type = 'rejected' THEN 1 ELSE 0 END) as rejected,
        COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN 1 END) as today,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as this_week,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as this_month
      FROM cookie_consent_logs
    `);

    res.json({ success: true, data: stats[0] });
  } catch (error) {
    console.error('Error fetching cookie consent stats:', error);
    res.status(500).json({
      success: false,
      message: 'İstatistikler getirilirken hata oluştu'
    });
  }
};

module.exports = {
  checkConsent,
  saveConsent,
  getAllConsents,
  getStats
};
