<?php
/**
 * API - Obtener datos para gráficos
 * Fecha: 13 de noviembre de 2025
 */

require_once '../config/config.php';

// Requiere autenticación para evitar acceso público
requireAuthentication();

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

try {
    $db = Database::getInstance();
    
    // Obtener datos de los últimos 7 días
    $chartData = $db->fetchAll(
        "SELECT 
            DATE(created_at) as date,
            COUNT(*) as message_count
         FROM conversations 
         WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
         GROUP BY DATE(created_at)
         ORDER BY date ASC"
    );
    
    // Formatear datos para Chart.js
    $labels = [];
    $data = [];
    
    foreach ($chartData as $row) {
        $labels[] = date('d/m', strtotime($row['date']));
        $data[] = (int)$row['message_count'];
    }
    
    echo json_encode([
        'labels' => $labels,
        'data' => $data
    ]);
    
} catch (Exception $e) {
    error_log("Error in get_chart_data.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Error interno del servidor']);
}
?>