<?php
/**
 * API de estadísticas para el panel principal
 */

header('Content-Type: application/json');

// Cargar variables de entorno
if (file_exists(__DIR__ . '/../../.env')) {
    $lines = file(__DIR__ . '/../../.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') === false) continue;
        list($key, $value) = explode('=', $line, 2);
        $_ENV[trim($key)] = trim($value);
    }
}

require_once __DIR__ . '/../database/connection.php';
require_once __DIR__. '/../auth/jwt.php';

// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'No autenticado']);
    exit;
}

try {
    $db = getDB();
    
    // Estadísticas de Discord
    $discordStats = [
        'users' => 0,
        'messages' => 0,
        'templates' => 0
    ];
    
    $stmt = $db->query("SELECT COUNT(*) as total FROM destinatarios_discord WHERE activo = 1 AND tipo = 'usuario'");
    $discordStats['users'] = $stmt->fetch()['total'];
    
    $stmt = $db->query("SELECT COUNT(*) as total FROM mensajes_discord WHERE estado = 'enviado'");
    $discordStats['messages'] = $stmt->fetch()['total'];
    
    $stmt = $db->query("SELECT COUNT(*) as total FROM plantillas_discord");
    $discordStats['templates'] = $stmt->fetch()['total'];
    
    // Estadísticas de Telegram
    $telegramStats = [
        'users' => 0,
        'messages' => 0,
        'templates' => 0
    ];
    
    $stmt = $db->query("SELECT COUNT(*) as total FROM destinatarios_telegram WHERE activo = 1 AND tipo = 'usuario'");
    $telegramStats['users'] = $stmt->fetch()['total'];
    
    $stmt = $db->query("SELECT COUNT(*) as total FROM mensajes_telegram WHERE estado = 'enviado'");
    $telegramStats['messages'] = $stmt->fetch()['total'];
    
    $stmt = $db->query("SELECT COUNT(*) as total FROM plantillas_telegram");
    $telegramStats['templates'] = $stmt->fetch()['total'];
    
    echo json_encode([
        'success' => true,
        'discord' => $discordStats,
        'telegram' => $telegramStats
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error al obtener estadísticas'
    ]);
    error_log('Error en stats.php: ' . $e->getMessage());
}
