<?php
/**
 * API - Exportar usuarios a CSV
 * Fecha: 13 de noviembre de 2025
 */

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

// Verificar autenticación
requireAuthentication();

// Headers para descarga de archivo
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="usuarios_whatsapp_' . date('Y-m-d') . '.csv"');
header('Cache-Control: no-cache, must-revalidate');

try {
    $db = Database::getInstance();
    
    // Obtener todos los usuarios con información adicional
    $users = $db->fetchAll(
        "SELECT 
            u.id,
            u.phone_number,
            u.name,
            u.email,
            u.status,
            u.created_at,
            u.updated_at,
            COUNT(c.id) as total_conversations,
            MAX(c.created_at) as last_activity
         FROM users u
         LEFT JOIN conversations c ON u.id = c.user_id
         GROUP BY u.id
         ORDER BY u.created_at DESC"
    );
    
    // Crear el archivo CSV
    $output = fopen('php://output', 'w');
    
    // BOM para UTF-8
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // Encabezados
    fputcsv($output, [
        'ID',
        'Teléfono',
        'Nombre',
        'Email',
        'Estado',
        'Total Mensajes',
        'Última Actividad',
        'Fecha Registro'
    ], ';');
    
    // Datos
    foreach ($users as $user) {
        fputcsv($output, [
            $user['id'],
            $user['phone_number'],
            $user['name'] ?? 'Sin nombre',
            $user['email'] ?? 'Sin email',
            $user['status'],
            $user['total_conversations'],
            $user['last_activity'] ? date('d/m/Y H:i', strtotime($user['last_activity'])) : 'Nunca',
            date('d/m/Y H:i', strtotime($user['created_at']))
        ], ';');
    }
    
    fclose($output);
    
} catch (Exception $e) {
    error_log("Error in export_users.php: " . $e->getMessage());
    
    // Cambiar headers para error
    header('Content-Type: application/json; charset=utf-8');
    header('Content-Disposition: inline');
    
    http_response_code(500);
    echo json_encode(['error' => 'Error interno del servidor']);
}
?>