= :date_from'; $params[':date_from'] = $dateFrom . ' 00:00:00'; } if ($dateTo !== '') { $where[] = 'c.created_at <= :date_to'; $params[':date_to'] = $dateTo . ' 23:59:59'; } $whereSQL = $where ? ('WHERE ' . implode(' AND ', $where)) : ''; // Nombre de archivo dinámico $filename = 'conversaciones_' . date('Y-m-d'); if ($dateFrom || $dateTo) $filename .= '_' . ($dateFrom ?: 'inicio') . '_a_' . ($dateTo ?: 'hoy'); $filename .= '.csv'; // Headers para descarga header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Cache-Control: no-cache, must-revalidate'); try { $db = Database::getInstance(); $pdo = $db->getConnection(); $sql = " SELECT c.id AS id, u.phone_number AS telefono, COALESCE(u.name, 'Sin nombre') AS nombre_usuario, c.direction AS direccion, c.message_type AS tipo_mensaje, c.status AS estado, CASE WHEN c.is_read = 1 THEN 'Sí' ELSE 'No' END AS leido, REPLACE(REPLACE(COALESCE(c.content,''), '\r\n', ' '), '\n', ' ') AS contenido, c.media_url AS url_media, c.filename AS archivo, c.created_at AS fecha_hora FROM conversations c INNER JOIN users u ON u.id = c.user_id $whereSQL ORDER BY c.created_at DESC LIMIT 50000 "; $stmt = $pdo->prepare($sql); $stmt->execute($params); $output = fopen('php://output', 'w'); // BOM UTF-8 para compatibilidad con Excel fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF)); // Encabezados CSV fputcsv($output, [ 'ID', 'Teléfono', 'Nombre Usuario', 'Dirección', 'Tipo Mensaje', 'Estado', 'Leído', 'Contenido', 'URL Media', 'Archivo', 'Fecha y Hora', ], ';'); // Filas while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { fputcsv($output, [ $row['id'], $row['telefono'], $row['nombre_usuario'], $row['direccion'], $row['tipo_mensaje'], $row['estado'], $row['leido'], $row['contenido'], $row['url_media'] ?? '', $row['archivo'] ?? '', $row['fecha_hora'] ? date('d/m/Y H:i:s', strtotime($row['fecha_hora'])) : '', ], ';'); } fclose($output); } catch (Exception $e) { error_log('export_conversations.php error: ' . $e->getMessage()); header('Content-Type: application/json; charset=utf-8'); header('Content-Disposition: inline'); http_response_code(500); echo json_encode(['error' => 'Error al exportar conversaciones']); }