<?php
/**
 * API - Obtener estadísticas del dashboard
 * Fecha: 13 de noviembre de 2025
 */

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

// Suprimir errores para obtener JSON limpio
error_reporting(E_ERROR | E_PARSE);

// Modo debug: desactivar autenticación si existe el parámetro debug
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';

if (!$debugMode) {
    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();
    
    // Total de usuarios
    $totalUsers = $db->fetch("SELECT COUNT(*) as count FROM users")['count'];
    
    // Mensajes hoy
    $conversationsToday = $db->fetch(
        "SELECT COUNT(*) as count FROM conversations WHERE DATE(created_at) = CURDATE()"
    )['count'];
    
    // Usuarios activos (último mes)
    $activeUsers = $db->fetch(
        "SELECT COUNT(DISTINCT user_id) as count FROM conversations 
         WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"
    )['count'];
    
    // Total de mensajes
    $totalconversations = $db->fetch("SELECT COUNT(*) as count FROM conversations")['count'];

    // Mensajes pendientes / no leídos: preferir columna is_read si existe, si no usar status = 'received'
    $unreadResult = $db->fetch(
        "SELECT COUNT(*) as count FROM conversations WHERE direction = 'incoming' AND ( (is_read IS NULL OR is_read = 0) OR status = 'received' )"
    );
    $unreadMessages = intval($unreadResult['count'] ?? 0);
    
    $stats = [
        'total_users' => (int)$totalUsers,
        'conversations_today' => (int)$conversationsToday,
        'active_users' => (int)$activeUsers,
        'total_conversations' => (int)$totalconversations,
        'unread_messages' => $unreadMessages
    ];
    
    echo json_encode($stats);
    
} catch (Exception $e) {
    error_log("Error in get_stats.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Error interno del servidor']);
}
?>