لماذا يظهر خطا بعد جلب اول امر للعلم الامر الاول يقو مبجلب المستخدمين الذين تم تسجيل دخولهم ولو لمرة واحدة على الاقل ولا يجلب جميع المستخدمين
للعلم الخطا
flutter: first_fetch
flutter: first_fetch
flutter: Response ignored: does not contain "ret" key.
flutter: Active Users Count: 0
flutter: Response ignored: does not contain "ret" key.
flutter: Active Users Count: 0
Restarted application in 2,610ms.
flutter: تم التحقق من التفعيل بنجاح
flutter: تم التحقق من التفعيل بنجاح
flutter: find : true
flutter: تم حفظ إصدار الراوتر بنجاح في: C:\Users\PC\Documents/MicropanelSecrt/router_version.json
flutter: تم حفظ إصدار الراوتر بنجاح في: C:\Users\PC\Documents/MicropanelSecrt/router_version.json
flutter: 6
flutter: All timers stopped
flutter: Client saved to AppSession
flutter: Active Users Count: 1
flutter: first_fetch
flutter: All timers stopped
flutter:     جاري الاتصال بالراوتر باستخدام:
    - العنوان: 172.16.0.1
    - المنفذ: 8728
    - اسم المستخدم: admin
    - كلمة المرور: ***********  // إخفاء كلمة المرور

flutter:     جاري الاتصال بالراوتر باستخدام:
    - العنوان: 172.16.0.1
    - المنفذ: 8728
    - اسم المستخدم: admin
    - كلمة المرور: ***********  // إخفاء كلمة المرور

flutter: ✅ تم الاتصال بالراوتر بنجاح
flutter: ✅ تم الاتصال بالراوتر بنجاح
flutter: بدء محاولة الجلب
flutter: بدء محاولة الجلب
flutter: استجابة المستخدمين: [[!re, =username=26433714], [!re, =username=26786985], [!re, =username=25298537], [!re, =username=24685596], [!re, =username=23101678], [!re, =username=28637740], [!re, =username=33692611], [!re, =username=26433714], [!re, =username=26786985], [!re, =username=25298537], [!re, =username=24685596], [!re, =username=23101678], [!re, =username=28637740], [!re, =username=33692611], [!re, =username=281082552], [!re, =username=281082552], [!re, =username=239764782], [!re, =username=292290298], [!re, =username=477144637], [!re, =username=492831853], [!re, =username=411475302], [!re, =username=239764782], [!re, =username=292290298], [!re, =username=477144637], [!re, =username=492831853], [!re, =username=411475302], [!re, =username=405936675], [!re, =username=432632792], [!re, =username=414721784], [!re, =username=429368313], [!re, =username=466964412], [!re, =username=499433467], [!re, =username=400772573], [!re, =username=409016860], [!re, =username=488581713], [!re, =username=487147103], [!re, =username=405936675], [!re, =username=432632792], [!re, =username=414721784], [!re, =username=429368313], [!re, =username=466964412], [!re, =username=499433467], [!re, =username=400772573], [!re, =username=409016860], [!re, =username=488581713], [!re, =username=487147103], [!re, =username=436834995], [!re, =username=456340836], [!re, =username=426151988], [!re, =username=482094924], [!re, =username=489055645], [!re, =username=422110745], [!re, =username=404914422], [!re, =username=408461996], [!re, =username=437416227], [!re, =username=499006622], [!re, =username=457060288], [!re, =username=476989357], [!re, =username=436834995], [!re, =username=456340836], [!re, =username=426151988], [!re, =username=482094924], [!re, =username=489055645], [!re, =username=422110745], [!re, =username=404914422], [!re, =username=408461996], [!re, =username=437416227], [!re, =username=499006622], [!re, =username=457060288], [!re, =username=476989357], [!re, =username=143796731], [!re, =username=109840077], [!re, =username=198346291], [!re, =username=107787155], [!re, =username=121410115], [!re, =username=139530133], [!re, =username=139003725], [!re, =username=177085617], [!re, =username=162400425], [!re, =username=100130380], [!re, =username=115705755], [!re, =username=122550776], [!re, =username=148640425], [!re, =username=162005279], [!re, =username=101599831], [!re, =username=153287553], [!re, =username=134942789], [!re, =username=166300683], [!re, =username=143796731], [!re, =username=109840077], [!re, =username=198346291], [!re, =username=107787155], [!re, =username=121410115], [!re, =username=139530133], [!re, =username=139003725], [!re, =username=177085617], [!re, =username=162400425], [!re, =username=100130380], [!re, =username=115705755], [!re, =username=122550776], [!re, =username=148640425], [!re, =username=162005279], [!re, =username=101599831], [!re, =username=153287553], [!re, =username=134942789], [!re, =username=166300683], [!re, =username=199232262], [!re, =username=199232262], [!re, =username=0192505321], [!re, =username=0123778133], [!re, =username=536893663], [!re, =username=0192505321], [!re, =username=0123778133], [!re, =username=536893663], [!re, =username=534938994], [!re, =username=592685630], [!re, =username=536126494], [!re, =username=563660814], [!re, =username=519529920], [!re, =username=585892537], [!re, =username=529704459], [!re, =username=561415502], [!re, =username=502226199], [!re, =username=511668762], [!re, =username=511222781], [!re, =username=534938994], [!re, =username=592685630], [!re, =username=536126494], [!re, =username=563660814], [!re, =username=519529920], [!re, =username=585892537], [!re, =username=529704459], [!re, =username=561415502], [!re, =username=502226199], [!re, =username=511668762], [!re, =username=511222781], [!re, =username=522365064], [!re, =username=593474508], [!re, =username=597713799], [!re, =username=549735707], [!re, =username=530651222], [!re, =username=534134924], [!re, =username=586210430], [!re, =username=514882155], [!re, =username=566216895], [!re, =username=590255735], [!re, =username=513272828], [!re, =username=511358269], [!re, =username=589055538], [!re, =username=562389876], [!re, =username=538631326], [!re, =username=577218608], [!re, =username=598086260], [!re, =username=589700495], [!re, =username=555787442], [!re, =username=524914862], [!re, =username=590851328], [!re, =username=547201987], [!re, =username=565597538], [!re, =username=591140150], [!re, =username=504376432], [!re, =username=588520387], [!re, =username=522365064], [!re, =username=593474508], [!re, =username=597713799], [!re, =username=549735707], [!re, =username=530651222], [!re, =username=534134924], [!re, =username=586210430], [!re, =username=514882155], [!re, =username=566216895], [!re, =username=590255735], [!re, =username=513272828], [!re, =username=511358269], [!re, =username=589055538], [!re, =username=562389876], [!re, =username=538631326], [!re, =username=577218608], [!re, =username=598086260], [!re, =username=589700495], [!re, =username=555787442], [!re, =username=524914862], [!re, =username=590851328], [!re, =username=547201987], [!re, =username=565597538], [!re, =username=591140150], [!re, =username=504376432], [!re, =username=588520387], [!re, =username=506283687], [!re, =username=506283687], [!re, =username=554373307], [!re, =username=589306863], [!re, =username=535085370], [!re, =username=571347166], [!re, =username=554373307], [!re, =username=589306863], [!re, =username=535085370], [!re, =username=571347166], [!re, =username=73342578], [!re, =username=76647954], [!re, =username=74246843], [!re, =username=74489684], [!re, =username=73354786], [!re, =username=73342578], [!re, =username=76647954], [!re, =username=74246843], [!re, =username=74489684], [!re, =username=73354786], [!re, =username=76786928], [!re, =username=76786928], [!re, =username=0103645476], [!re, =username=0154560426], [!re, =username=0103645476], [!re, =username=0154560426], [!re, =username=0183324600], [!re, =username=0182965190], [!re, =username=0192729097], [!re, =username=0168340058], [!re, =username=0188041058], [!re, =username=0185941000], [!re, =username=0166667988], [!re, =username=0190643359], [!re, =username=0138119127], [!re, =username=0136765530], [!re, =username=0184138890], [!re, =username=0113063850], [!re, =username=0161457748], [!re, =username=0101717500], [!re, =username=0136150597], [!re, =username=0192609744], [!re, =username=0170798080], [!re, =username=0160903399], [!re, =username=0183324600], [!re, =username=0182965190], [!re, =username=0192729097], [!re, =username=0168340058], [!re, =username=0188041058], [!re, =username=0185941000], [!re, =username=0166667988], [!re, =username=0190643359], [!re, =username=0138119127], [!re, =username=0136765530], [!re, =username=0184138890], [!re, =username=0113063850], [!re, =username=0161457748], [!re, =username=0101717500], [!re, =username=0136150597], [!re, =username=0192609744], [!re, =username=0170798080], [!re, =username=0160903399], [!re, =username=0144637903], [!re, =username=0132775204], [!re, =username=0181545734], [!re, =username=0137833982], [!re, =username=0122751666], [!re, =username=0156087348], [!re, =username=0137181897], [!re, =username=0157524575], [!re, =username=0101007514], [!re, =username=0146912639], [!re, =username=0116502132], [!re, =username=0107838731], [!re, =username=0155263931], [!re, =username=0101280609], [!re, =username=0180195607], [!re, =username=0196810029], [!re, =username=0155033821], [!re, =username=0174679032], [!re, =username=0178831172], [!re, =username=0157385412], [!re, =username=0144972019], [!re, =username=0108939552], [!re, =username=0144637903], [!re, =username=0132775204], [!re, =username=0181545734], [!re, =username=0137833982], [!re, =username=0122751666], [!re, =username=0156087348], [!re, =username=0137181897], [!re, =username=0157524575], [!re, =username=0101007514], [!re, =username=0146912639], [!re, =username=0116502132], [!re, =username=0107838731], [!re, =username=0155263931], [!re, =username=0101280609], [!re, =username=0180195607], [!re, =username=0196810029], [!re, =username=0155033821], [!re, =username=0174679032], [!re, =username=0178831172], [!re, =username=0157385412], [!re, =username=0144972019], [!re, =username=0108939552], [!re, =username=0181438026], [!re, =username=0174240712], [!re, =username=0145737808], [!re, =username=0129472942], [!re, =username=0121543989], [!re, =username=0135418713], [!re, =username=0143647019], [!re, =username=0124692285], [!re, =username=0109862359], [!re, =username=0181379563], [!re, =username=0121472808], [!re, =username=0181438026], [!re, =username=0174240712], [!re, =username=0145737808], [!re, =username=0129472942], [!re, =username=0121543989], [!re, =username=0135418713], [!re, =username=0143647019], [!re, =username=0124692285], [!re, =username=0109862359], [!re, =username=0181379563], [!re, =username=0121472808], [!re, =username=0147678346], [!re, =username=0167922880], [!re, =username=0184976684], [!re, =username=0118519438], [!re, =username=0147678346], [!re, =username=0167922880], [!re, =username=0184976684], [!re, =username=0118519438], [!re, =username=72033087], [!re, =username=74268643], [!re, =username=72033087], [!re, =username=74268643], [!re, =username=ameersh], [!re, =username=ameetsh], [!re, =username=232417], [!re, =username=2324174], [!done]]
flutter: تم جلب 332 مستخدم
flutter: استجابة المستخدمين: [[!re, =username=ameersh], [!re, =username=ameetsh], [!re, =username=232417], [!re, =username=2324174], [!done]]
flutter: تم جلب 4 مستخدم
flutter: Error in _fetchDataFromRouter: Bad state: StreamSink is bound to a stream
flutter: Stack trace: #0      _StreamSinkImpl._controller (dart:io/io_sink.dart:238:7)
flutter: #1      _StreamSinkImpl.add (dart:io/io_sink.dart:155:5)
flutter: #2      _Socket.add (dart:io-patch/socket_patch.dart:2774:38)
flutter: #3      MicroPanelSales.sendSentence (package:micro_panel/UserManagerSales.dart:2698:13)
flutter: #4      _UserManagerSalesState._fetchDataFromRouter (package:micro_panel/UserManagerSales.dart:380:30)
flutter: <asynchronous suspension>
flutter:
flutter: Error fetching or decrypting config from Firebase: ClientException with SocketException: Failed host lookup: 'micropanel-b67e0-default-rtdb.firebaseio.com' (OS Error: This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server.

, errno = 11002), uri=https://micropanel-b67e0-default-rtdb.firebaseio.com/information.json
#0      IOClient.send (package:http/src/io_client.dart:154:7)
<asynchronous suspension>
#1      BaseClient._sendUnstreamed (package:http/src/base_client.dart:93:32)
<asynchronous suspension>
#2      _withClient (package:http/http.dart:167:12)
<asynchronous suspension>
#3      _LoginState.fetchJsonFromFirebase (package:micro_panel/Login.dart:724:24)
<asynchronous suspension>

[ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: Exception: فشل في جلب أو فك تشفير الإعدادات
#0      _LoginState.fetchJsonFromFirebase (package:micro_panel/Login.dart:768:7)
<asynchronous suspension>

[ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: ClientException with SocketException: Failed host lookup: 'micropanel-b67e0-default-rtdb.firebaseio.com' (OS Error: This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server.

, errno = 11002), uri=https://micropanel-b67e0-default-rtdb.firebaseio.com/triler.json
#0      IOClient.send (package:http/src/io_client.dart:154:7)
<asynchronous suspension>
#1      BaseClient._sendUnstreamed (package:http/src/base_client.dart:93:32)
<asynchronous suspension>
#2      _withClient (package:http/http.dart:167:12)
<asynchronous suspension>
#3      _LoginState.checkStatus.<anonymous closure> (package:micro_panel/Login.dart:2864:30)
<asynchronous suspension>



اما الكود بالكامل
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' as intl;
import 'package:micro_panel/AboutApp.dart';
import 'package:micro_panel/AddHotspotUser.dart';
import 'package:micro_panel/AddUserManagerUser.dart';
import 'package:micro_panel/HelpDesk.dart';
import 'package:micro_panel/HomePage.dart';
import 'package:micro_panel/HotspotProfile.dart';
import 'package:micro_panel/Login.dart';
import 'package:micro_panel/SendNotes.dart';
import 'package:micro_panel/Transmitters.dart';
import 'package:micro_panel/UserManagerProfile.dart';
import 'package:micro_panel/UserManagerReport.dart';
import 'package:micro_panel/UserManagerUserList.dart';
import 'package:micro_panel/backupSN.dart';
import 'package:micro_panel/free_rebiuld.dart';
import 'package:micro_panel/hotspotUserList.dart';
import 'package:path_provider/path_provider.dart';
import 'package:router_os_client/router_os_client.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';
import 'package:file_picker/file_picker.dart';

class UserManagerSales extends StatefulWidget {
  final RouterOSClient client;
  const UserManagerSales({super.key, required this.client});

  @override
  State<UserManagerSales> createState() => _UserManagerSalesState();
}

class _UserManagerSalesState extends State<UserManagerSales> {
  Color _primaryColor = const Color(0xFF3B82F6);
  Color _backgroundColor = const Color(0xFF0A192F);
  Color _cardColor = const Color(0xFF172A46);
  Color _textColor = Colors.white;
  int _currentIndex = 0;

  final ValueNotifier<bool> _isLoadingNotifier = ValueNotifier(false);
  final ValueNotifier<String?> _errorNotifier = ValueNotifier(null);

  List<Map<String, dynamic>> _filteredSessions = [];

  bool isHotspotExpanded = false;
  bool isUserManagerExpanded = true;
  bool isSettingsExpanded = false;
  bool isHelpExpanded = false;

  late MicroPanelSales _MicroPanelSales;

  @override
  void initState() {
    super.initState();
    // تعيين القيم الافتراضية للتواريخ والأوقات
    final now = DateTime.now();

    _startDate = now.subtract(Duration(days: 1));
    _endDate = now;

    _startTime = TimeOfDay(hour: 0, minute: 0);
    _endTime = TimeOfDay(hour: now.hour, minute: now.minute);

    _MicroPanelSales = MicroPanelSales(client: widget.client);
    _connectAndFetchData().then((_) {
      setState(() {
        _filterDataByDateRange();
      });
    });
    _connectAndFetchData();
  }

  Future<void> _generatePdf() async {
    final pdf = pw.Document();

    // حساب الإجماليات
    final userCount = _filteredSessions.length;
    final totalPrice = _filteredSessions.fold(0, (sum, user) {
      final price = int.tryParse(user['price']?.toString() ?? '0') ?? 0;
      return sum + (price ~/ 100);
    });

    // تنسيق التاريخ والوقت
    final dateFormat = intl.DateFormat('yyyy/MM/dd HH:mm');
    final now = DateTime.now();
    final startDateTime = DateTime(
      _startDate!.year,
      _startDate!.month,
      _startDate!.day,
      _startTime!.hour,
      _startTime!.minute,
    );
    final endDateTime = DateTime(
      _endDate!.year,
      _endDate!.month,
      _endDate!.day,
      _endTime!.hour,
      _endTime!.minute,
    );

    pdf.addPage(
      pw.MultiPage(
        pageFormat: PdfPageFormat.a4,
        textDirection: pw.TextDirection.rtl,
        theme: pw.ThemeData.withFont(
          base: await PdfGoogleFonts.tajawalRegular(),
          bold: await PdfGoogleFonts.tajawalBold(),
        ),
        build:
            (pw.Context context) => [
              pw.Column(
                crossAxisAlignment: pw.CrossAxisAlignment.start,
                children: [
                  pw.Header(
                    level: 0,
                    child: pw.Row(
                      mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
                      children: [
                        pw.Text(
                          'تقرير اليوزر مانجر',
                          style: pw.TextStyle(
                            fontSize: 24,
                            fontWeight: pw.FontWeight.bold,
                          ),
                        ),
                        pw.Text(
                          dateFormat.format(now),
                          style: pw.TextStyle(fontSize: 12),
                        ),
                      ],
                    ),
                  ),
                  pw.SizedBox(height: 10),
                  pw.Text(
                    'الفترة الزمنية: ${dateFormat.format(startDateTime)} - ${dateFormat.format(endDateTime)}',
                    style: pw.TextStyle(fontSize: 12),
                  ),
                  pw.Text(
                    'عدد المستخدمين: $userCount',
                    style: pw.TextStyle(fontSize: 12),
                  ),
                  pw.Text(
                    'الإجمالي: $totalPrice',
                    style: pw.TextStyle(fontSize: 12),
                  ),
                  pw.SizedBox(height: 20),

                  /// جدول احترافي
                  pw.Table(
                    border: pw.TableBorder.all(
                      color: PdfColors.grey400,
                      width: 0.5,
                    ),
                    tableWidth: pw.TableWidth.max,
                    defaultVerticalAlignment:
                        pw.TableCellVerticalAlignment.middle,
                    children: [
                      /// رأس الجدول
                      pw.TableRow(
                        decoration: pw.BoxDecoration(
                          color: PdfColor.fromHex('#3B82F6'),
                        ),
                        children: [
                          pw.Padding(
                            padding: const pw.EdgeInsets.all(6),
                            child: pw.Text(
                              'اسم المستخدم',
                              style: pw.TextStyle(
                                fontWeight: pw.FontWeight.bold,
                                color: PdfColors.white,
                              ),
                              textAlign: pw.TextAlign.center,
                            ),
                          ),
                          pw.Padding(
                            padding: const pw.EdgeInsets.all(6),
                            child: pw.Text(
                              'السعر',
                              style: pw.TextStyle(
                                fontWeight: pw.FontWeight.bold,
                                color: PdfColors.white,
                              ),
                              textAlign: pw.TextAlign.center,
                            ),
                          ),
                          pw.Padding(
                            padding: const pw.EdgeInsets.all(6),
                            child: pw.Text(
                              'أول تسجيل دخول',
                              style: pw.TextStyle(
                                fontWeight: pw.FontWeight.bold,
                                color: PdfColors.white,
                              ),
                              textAlign: pw.TextAlign.center,
                            ),
                          ),
                          pw.Padding(
                            padding: const pw.EdgeInsets.all(6),
                            child: pw.Text(
                              'قطعة البث',
                              style: pw.TextStyle(
                                fontWeight: pw.FontWeight.bold,
                                color: PdfColors.white,
                              ),
                              textAlign: pw.TextAlign.center,
                            ),
                          ),
                        ],
                      ),

                      /// الصفوف
                      ..._filteredSessions.asMap().entries.map((entry) {
                        final index = entry.key;
                        final user = entry.value;
                        final isEven = index % 2 == 0;
                        return pw.TableRow(
                          decoration: pw.BoxDecoration(
                            color: isEven ? PdfColors.grey100 : PdfColors.white,
                          ),
                          children: [
                            pw.Padding(
                              padding: const pw.EdgeInsets.all(5),
                              child: pw.Text(
                                user['username']?.toString() ?? 'غير معروف',
                                textAlign: pw.TextAlign.center,
                              ),
                            ),
                            pw.Padding(
                              padding: const pw.EdgeInsets.all(5),
                              child: pw.Text(
                                user['price'] != null
                                    ? (int.parse(user['price'].toString()) ~/
                                            100)
                                        .toString()
                                    : '0',
                                textAlign: pw.TextAlign.center,
                              ),
                            ),
                            pw.Padding(
                              padding: const pw.EdgeInsets.all(5),
                              child: pw.Text(
                                user['from-time']?.toString() ?? 'غير معروف',
                                textAlign: pw.TextAlign.center,
                              ),
                            ),
                            pw.Padding(
                              padding: const pw.EdgeInsets.all(5),
                              child: pw.Text(
                                user['nas-port-id']?.toString() ?? 'غير معروف',
                                textAlign: pw.TextAlign.center,
                              ),
                            ),
                          ],
                        );
                      }).toList(),
                    ],
                  ),
                ],
              ),
            ],
      ),
    );

    try {
      // محاولة الطباعة المباشرة
      await Printing.layoutPdf(
        onLayout: (PdfPageFormat format) async => pdf.save(),
      );
    } catch (e) {
      // حفظ الملف في مسار يختاره المستخدم
      final String? outputPath = await FilePicker.platform.saveFile(
        dialogTitle: 'حفظ تقرير اليوزر مانجر',
        fileName:
            'user_manager_report_${DateTime.now().millisecondsSinceEpoch}.pdf',
        allowedExtensions: ['pdf'],
        type: FileType.custom,
      );

      if (outputPath != null) {
        final file = File(outputPath);
        await file.writeAsBytes(await pdf.save());

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('تم حفظ التقرير بنجاح في: $outputPath'),
              duration: Duration(seconds: 5),
            ),
          );
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('تم إلغاء عملية الحفظ'),
              duration: Duration(seconds: 2),
            ),
          );
        }
      }
    }
  }

  Future<void> _connectAndFetchData() async {
    try {
      _isLoadingNotifier.value = true;

      // عرض بيانات الاتصال قبل المحاولة
      print('''
    جاري الاتصال بالراوتر باستخدام:
    - العنوان: ${_MicroPanelSales.host}
    - المنفذ: ${_MicroPanelSales.port}
    - اسم المستخدم: ${_MicroPanelSales.user}
    - كلمة المرور: ${_MicroPanelSales.pass.replaceAll(RegExp(r'.'), '*')}  // إخفاء كلمة المرور
    ''');

      await _MicroPanelSales.connect();
      print('✅ تم الاتصال بالراوتر بنجاح');

      _fetchDataFromRouter();
    } catch (e) {
      _errorNotifier.value = 'فشل الاتصال بالراوتر: ${e.toString()}';
      _isLoadingNotifier.value = false;
      print('❌ فشل الاتصال: $e');
    }
  }

  // متغيرات جديدة لتخزين التواريخ
  DateTime? _startDate;
  DateTime? _endDate;
  TimeOfDay? _startTime;
  TimeOfDay? _endTime;
  List<Map<String, dynamic>> _allSessions = []; // لتخزين جميع البيانات

  Future<void> _fetchDataFromRouter() async {
    final routerVersion = await _getRouterVersion();
    final isVersion7 = routerVersion >= 7;
    try {
      _isLoadingNotifier.value = true;
      _errorNotifier.value = null;
      print('بدء محاولة الجلب');

      // 1. جلب قائمة المستخدمين وتخزينها في مصفوفة أولية
      await _MicroPanelSales.sendSentence([
        isVersion7
            ? ' user-manager/user-profile/print'
            : '/tool/user-manager/user/print',
        if (!isVersion7) '?download-used',
        isVersion7 ? '=.proplist=user' : '=.proplist=username',
      ]);

      final usersResponse = await _MicroPanelSales._readSentences();
      print('استجابة المستخدمين: $usersResponse');

      List<Map<String, dynamic>> userList = [];
      for (var sentence in usersResponse) {
        if (sentence.isNotEmpty && sentence.first == '!re') {
          Map<String, dynamic> userData = {};
          for (var token in sentence.skip(1)) {
            if (token.startsWith('=')) {
              final parts = token.substring(1).split('=');
              if (parts.length >= 2) {
                userData[parts[0]] = parts.sublist(1).join('=');
              }
            }
          }
          if (userData.isNotEmpty && userData.containsKey('username')) {
            userList.add(userData);
          }
        }
      }

      print('تم جلب ${userList.length} مستخدم');

      // 2. جلب جميع بيانات الدفع لكل المستخدمين وتخزينها في مصفوفة
      await _MicroPanelSales.sendSentence([
        '/tool/user-manager/payment/print',
        '=.proplist=user,price,time',
      ]);
      final paymentsResponse = await _MicroPanelSales._readSentences();

      List<Map<String, dynamic>> allPayments = [];
      for (var sentence in paymentsResponse) {
        if (sentence.isNotEmpty && sentence.first == '!re') {
          Map<String, dynamic> paymentData = {};
          for (var token in sentence.skip(1)) {
            if (token.startsWith('=')) {
              final parts = token.substring(1).split('=');
              if (parts.length >= 2) {
                paymentData[parts[0]] = parts.sublist(1).join('=');
              }
            }
          }
          if (paymentData.isNotEmpty && paymentData.containsKey('user')) {
            allPayments.add(paymentData);
          }
        }
      }

      // 3. جلب جميع بيانات الجلسات لكل المستخدمين وتخزينها في مصفوفة
      await _MicroPanelSales.sendSentence([
        '/tool/user-manager/session/print',
        '=.proplist=user,nas-port-id,from-time',
      ]);
      final sessionsResponse = await _MicroPanelSales._readSentences();

      List<Map<String, dynamic>> allSessions = [];
      for (var sentence in sessionsResponse) {
        if (sentence.isNotEmpty && sentence.first == '!re') {
          Map<String, dynamic> sessionData = {};
          for (var token in sentence.skip(1)) {
            if (token.startsWith('=')) {
              final parts = token.substring(1).split('=');
              if (parts.length >= 2) {
                sessionData[parts[0]] = parts.sublist(1).join('=');
              }
            }
          }
          if (sessionData.isNotEmpty && sessionData.containsKey('user')) {
            allSessions.add(sessionData);
          }
        }
      }

      // 4. ربط البيانات من المصفوفات الثلاث مع بعضها البعض
      List<Map<String, dynamic>> allData = [];

      for (var user in userList) {
        final username = user['username'];
        if (username == null) continue;

        try {
          // تصفية مدفوعات هذا المستخدم
          final userPayments =
              allPayments.where((p) => p['user'] == username).toList();

          // تصفية جلسات هذا المستخدم
          final userSessions =
              allSessions.where((s) => s['user'] == username).toList();

          // دمج البيانات لكل مستخدم
          allData.add({
            'username': username,
            'price':
                userPayments.isNotEmpty
                    ? userPayments.last['price'] ?? '0'
                    : '0',
            'from-time':
                userSessions.isNotEmpty
                    ? userSessions.first['from-time'] ?? 'غير معروف'
                    : 'غير معروف',
            'nas-port-id':
                userSessions.isNotEmpty
                    ? userSessions.first['nas-port-id'] ?? 'غير معروف'
                    : 'غير معروف',
            'parsed-time':
                userSessions.isNotEmpty
                    ? _parseMikrotikDateTime(
                      userSessions.first['from-time'] ?? '',
                    )
                    : null,
          });
        } catch (e) {
          debugPrint('Error processing data for user $username: $e');
          // إضافة بيانات أساسية حتى لو فشل جلب بعض البيانات
          allData.add({
            'username': username,
            'price': '0',
            'from-time': 'غير معروف',
            'nas-port-id': 'غير معروف',
            'parsed-time': null,
          });
        }
      }

      // 5. تطبيق الفلترة على البيانات المدمجة
      setState(() {
        _allSessions = allData;
      });
      _filterDataByDateRange();

      _isLoadingNotifier.value = false;
    } catch (e, stackTrace) {
      _errorNotifier.value = 'حدث خطأ أثناء جلب البيانات: ${e.toString()}';
      _isLoadingNotifier.value = false;
      debugPrint('Error in _fetchDataFromRouter: $e');
      debugPrint('Stack trace: $stackTrace');

      // محاولة إعادة الاتصال
      try {
        await _MicroPanelSales.connect();
      } catch (e) {
        debugPrint('Failed to reconnect: $e');
      }
    }
  }

  // دالة لتصفية البيانات حسب الفترة الزمنية
  void _filterDataByDateRange() {
    if (_startDate == null ||
        _endDate == null ||
        _startTime == null ||
        _endTime == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('الرجاء تحديد الفترة الزمنية أولاً')),
      );
      return;
    }

    // دمج التاريخ والوقت
    final startDateTime = DateTime(
      _startDate!.year,
      _startDate!.month,
      _startDate!.day,
      _startTime!.hour,
      _startTime!.minute,
    );

    final endDateTime = DateTime(
      _endDate!.year,
      _endDate!.month,
      _endDate!.day,
      _endTime!.hour,
      _endTime!.minute,
    );

    setState(() {
      _filteredSessions =
          _allSessions.where((session) {
            final sessionTime = session['parsed-time'];
            if (sessionTime == null) return false;

            return sessionTime.isAfter(startDateTime) &&
                sessionTime.isBefore(endDateTime);
          }).toList();
    });
  }

  // دالة لاختيار التاريخ
  Future<void> _selectDate(BuildContext context, bool isStartDate) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );
    if (picked != null) {
      setState(() {
        if (isStartDate) {
          _startDate = picked;
        } else {
          _endDate = picked;
        }
      });

      if (_startDate != null &&
          _endDate != null &&
          _startTime != null &&
          _endTime != null) {
        _filterDataByDateRange();
      }
    }
  }

  // دالة لاختيار الوقت
  Future<void> _selectTime(BuildContext context, bool isStartTime) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );
    if (picked != null) {
      setState(() {
        if (isStartTime) {
          _startTime = picked;
        } else {
          _endTime = picked;
        }
      });
      // محاولة تطبيق الفلترة إذا كانت البيانات كاملة
      if (_startDate != null &&
          _endDate != null &&
          _startTime != null &&
          _endTime != null) {
        _filterDataByDateRange();
      }
    }
  }

  // إضافة واجهة اختيار التاريخ والوقت في ويدجت البناء
  Widget _buildDateRangeSelector() {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 16,
        vertical: MediaQuery.of(context).size.width > 600 ? 24 : 16,
      ),
      decoration: BoxDecoration(
        color: _cardColor,
        borderRadius: BorderRadius.circular(12),
      ),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final isWideScreen = constraints.maxWidth > 600;

          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // عنوان القسم
              Row(
                children: [
                  Icon(Icons.calendar_today, color: Colors.white70, size: 20),
                  SizedBox(width: 8),
                  Text(
                    'تحديد النطاق الزمني',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: isWideScreen ? 18 : 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 16),

              // عرض أفقي للشاشات الكبيرة وعمودي للصغيرة
              isWideScreen ? _buildWideLayout() : _buildMobileLayoutTimer(),

              SizedBox(height: 16),

              // زر التطبيق
              SizedBox.shrink(),
            ],
          );
        },
      ),
    );
  }

  Widget _buildWideLayout() {
    return Row(
      children: [
        Expanded(child: _buildDatePicker(true)), // تاريخ البداية
        SizedBox(width: 16),
        Center(child: Icon(Icons.arrow_forward, color: Colors.white54)),
        SizedBox(width: 16),
        Expanded(child: _buildDatePicker(false)), // تاريخ النهاية
      ],
    );
  }

  Widget _buildMobileLayoutTimer() {
    return Column(
      children: [
        _buildDatePicker(true), // تاريخ البداية
        SizedBox(height: 12),

        _buildDatePicker(false), // تاريخ النهاية
      ],
    );
  }

  Widget _buildDatePicker(bool isStartDate) {
    final bool isMobile = MediaQuery.of(context).size.width < 600;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (!isMobile)
          Text(
            isStartDate ? 'من تاريخ:' : 'إلى تاريخ:',
            style: TextStyle(color: Colors.white70, fontSize: 13), // أقل قليلاً
          ),
        SizedBox(height: isMobile ? 2 : 6), // قلل الارتفاع

        if (isMobile)
          Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: () async {
                await _selectDate(context, isStartDate);
                await _selectTime(context, isStartDate);
              },
              child: Container(
                padding: EdgeInsets.all(8), // قلل الـ padding
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.2),
                  border: Border.all(color: Colors.white24),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Row(
                  children: [
                    Icon(Icons.calendar_month, color: Colors.white70, size: 20),
                    SizedBox(width: 6),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            isStartDate ? 'تاريخ البداية' : 'تاريخ النهاية',
                            style: TextStyle(
                              color: Colors.white70,
                              fontSize: 11,
                            ),
                          ),
                          SizedBox(height: 1),
                          Text(
                            isStartDate
                                ? (_startDate != null
                                    ? '${intl.DateFormat('yyyy/MM/dd').format(_startDate!)} ${_startTime?.format(context) ?? ''}'
                                    : 'اختر التاريخ والوقت')
                                : (_endDate != null
                                    ? '${intl.DateFormat('yyyy/MM/dd').format(_endDate!)} ${_endTime?.format(context) ?? ''}'
                                    : 'اختر التاريخ والوقت'),
                            style: TextStyle(color: Colors.white, fontSize: 13),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          )
        else
          Column(
            children: [
              Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: () => _selectDate(context, isStartDate),
                  child: Container(
                    padding: EdgeInsets.all(8), // قلل الـ padding
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.2),
                      border: Border.all(color: Colors.white24),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.calendar_month,
                          color: Colors.white70,
                          size: 20,
                        ),
                        SizedBox(width: 6),
                        Text(
                          isStartDate
                              ? (_startDate != null
                                  ? intl.DateFormat(
                                    'yyyy/MM/dd',
                                  ).format(_startDate!)
                                  : 'اختر التاريخ')
                              : (_endDate != null
                                  ? intl.DateFormat(
                                    'yyyy/MM/dd',
                                  ).format(_endDate!)
                                  : 'اختر التاريخ'),
                          style: TextStyle(color: Colors.white, fontSize: 13),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              SizedBox(height: 6),
              Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: () => _selectTime(context, isStartDate),
                  child: Container(
                    padding: EdgeInsets.all(8), // قلل الـ padding
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.2),
                      border: Border.all(color: Colors.white24),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.access_time,
                          color: Colors.white70,
                          size: 20,
                        ),
                        SizedBox(width: 6),
                        Text(
                          isStartDate
                              ? (_startTime != null
                                  ? _startTime!.format(context)
                                  : 'اختر الوقت')
                              : (_endTime != null
                                  ? _endTime!.format(context)
                                  : 'اختر الوقت'),
                          style: TextStyle(color: Colors.white, fontSize: 13),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
      ],
    );
  }

  Widget _buildDataTable() {
    return LayoutBuilder(
      builder: (context, constraints) {
        // إذا لم يكن هناك بيانات
        if (_filteredSessions.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.people_outline,
                  size: 64,
                  color: Colors.white.withOpacity(0.3),
                ),
                SizedBox(height: 16),
                Text(
                  'لا يوجد مستخدمين',
                  style: TextStyle(
                    color: Colors.white.withOpacity(0.5),
                    fontSize: 18,
                  ),
                ),
              ],
            ),
          );
        }

        // للشاشات الكبيرة (أعرض من 600 بكسل)
        if (constraints.maxWidth > 600) {
          return SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Container(
              width: double.infinity,
              padding: EdgeInsets.all(8),
              child: DataTable(
                columnSpacing: 20,
                horizontalMargin: 12,
                headingRowColor: MaterialStateProperty.resolveWith<Color>(
                  (Set<MaterialState> states) => _primaryColor.withOpacity(0.2),
                ),
                columns: const [
                  DataColumn(
                    label: Text(
                      'اسم المستخدم',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'السعر',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'أول تسجيل دخول',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'قطعة البث',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
                rows:
                    _filteredSessions.map((data) {
                      return DataRow(
                        cells: [
                          DataCell(
                            Text(
                              data['username']?.toString() ?? 'غير معروف',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          DataCell(
                            Text(
                              data['price'] != null
                                  ? (int.parse(data['price'].toString()) ~/ 100)
                                      .toString()
                                  : 'غير معروف',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          DataCell(
                            Text(
                              data['from-time']?.toString() ?? 'غير معروف',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          DataCell(
                            Text(
                              data['nas-port-id']?.toString() ?? 'غير معروف',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                        ],
                      );
                    }).toList(),
              ),
            ),
          );
        }
        // للشاشات الصغيرة (الهواتف)
        else {
          return ListView.builder(
            itemCount: _filteredSessions.length,
            itemBuilder: (context, index) {
              final data = _filteredSessions[index];
              return Card(
                margin: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
                color: _cardColor,
                child: Padding(
                  padding: EdgeInsets.all(12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildMobileTableRow(
                        'اسم المستخدم',
                        data['username']?.toString() ?? 'غير معروف',
                      ),
                      Divider(color: Colors.white24),
                      _buildMobileTableRow(
                        'السعر',
                        data['price'] != null
                            ? (int.parse(data['price'].toString()) ~/ 100)
                                .toString()
                            : 'غير معروف',
                      ),
                      Divider(color: Colors.white24),
                      _buildMobileTableRow(
                        'أول تسجيل دخول',
                        data['from-time']?.toString() ?? 'غير معروف',
                      ),
                      Divider(color: Colors.white24),
                      _buildMobileTableRow(
                        'قطعة البث',
                        data['nas-port-id']?.toString() ?? 'غير معروف',
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        }
      },
    );
  }

  // دالة مساعدة لعرض الصفوف في الوضع الموبايل
  Widget _buildMobileTableRow(String title, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          title,
          style: TextStyle(
            color: _primaryColor,
            fontWeight: FontWeight.bold,
            fontSize: 14,
          ),
        ),
        Text(value, style: TextStyle(color: Colors.white, fontSize: 14)),
      ],
    );
  }

  String _formatBytes(int bytes) {
    if (bytes <= 0) return "0 B";
    const suffixes = ["B", "KB", "MB", "GB", "TB"];
    var i = (log(bytes) / log(1024)).floor();
    return '${(bytes / pow(1024, i)).toStringAsFixed(2)} ${suffixes[i]}';
  }

  // دالة مساعدة لتحويل صيغة MikroTik "Jul/26/2025 13:59:22" إلى DateTime
  DateTime? _parseMikrotikDateTime(String mikDate) {
    try {
      // صيغة MikroTik: "Jul/26/2025 13:59:22"
      // نحتاج نعيد صياغتها لصيغة يدعمها DateTime.parse:
      final parts = mikDate.split(' ');
      if (parts.length != 2) return null;
      final datePart = parts[0]; // Jul/26/2025
      final timePart = parts[1]; // 13:59:22

      final dateParts = datePart.split('/');
      if (dateParts.length != 3) return null;

      final monthAbbr = dateParts[0].toLowerCase();
      final monthMap = {
        'jan': 1,
        'feb': 2,
        'mar': 3,
        'apr': 4,
        'may': 5,
        'jun': 6,
        'jul': 7,
        'aug': 8,
        'sep': 9,
        'oct': 10,
        'nov': 11,
        'dec': 12,
      };

      final month = monthMap[monthAbbr];
      if (month == null) return null;

      final day = int.tryParse(dateParts[1]);
      final year = int.tryParse(dateParts[2]);

      if (day == null || year == null) return null;

      final dtString =
          '$year-${month.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')} $timePart';
      return DateTime.parse(dtString);
    } catch (e) {
      return null;
    }
  }

  Future<int> _getRouterVersion() async {
    try {
      final maindirectory = await getApplicationDocumentsDirectory();
      final saveDirectory = Directory('${maindirectory.path}/MicropanelSecrt');
      if (!await saveDirectory.exists()) {
        await saveDirectory.create(recursive: true);
      }
      final file = File('${saveDirectory.path}/router_version.json');

      if (await file.exists()) {
        final content = await file.readAsString();
        final jsonData = jsonDecode(content);
        return int.tryParse(jsonData['router_version'].toString()) ?? 6;
      }
      return 6;
    } catch (e) {
      debugPrint('Error reading version file: $e');
      return 6;
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _onItemTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: LayoutBuilder(
        builder: (context, constraints) {
          if (constraints.maxWidth > 800) {
            return _buildDesktopLayoutTimer(context);
          } else {
            return _buildMobileLayout(context);
          }
        },
      ),
    );
  }

  Widget _buildDesktopLayoutTimer(BuildContext context) {
    return Scaffold(
      backgroundColor: _backgroundColor,
      body: Row(
        children: [
          _buildDesktopNavigation(),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    _backgroundColor.withOpacity(0.9),
                    _backgroundColor.withOpacity(0.7),
                  ],
                ),
              ),
              child: _buildMainContent(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMobileLayout(BuildContext context) {
    // حساب عدد المستخدمين وإجمالي السعر
    final userCount = _filteredSessions.length;
    final totalPrice = _filteredSessions.fold(0, (sum, user) {
      final price = int.tryParse(user['price']?.toString() ?? '0') ?? 0;
      return sum + (price ~/ 100); // القسمة على 100 لتحويل السعر
    });

    return Scaffold(
      backgroundColor: _backgroundColor,
      drawer: _buildUniversalDrawer(),
      appBar: AppBar(
        title: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text(
              'تقارير اليوزر مانجر',
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: Colors.white,
                fontSize: 17,
              ),
            ),
            if (userCount > 0)
              Text(
                'المستخدمين: $userCount | الإجمالي: $totalPrice',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  color: Colors.white70,
                  fontSize: 12,
                ),
              ),
          ],
        ),
        backgroundColor: _backgroundColor,
        centerTitle: true,
        elevation: 0,
        leading: Builder(
          builder:
              (context) => IconButton(
                icon: Icon(Icons.menu_rounded, color: _textColor),
                onPressed: () => Scaffold.of(context).openDrawer(),
              ),
        ),
        actions: [
          if (_filteredSessions.isNotEmpty)
            IconButton(
              icon: Icon(Icons.picture_as_pdf, color: _primaryColor),
              onPressed: _generatePdf,
              tooltip: 'تصدير إلى PDF',
            ),
        ],
      ),
      body: _buildMainContent(showHeader: false),
    );
  }

  Widget _buildDesktopNavigation() {
    return SingleChildScrollView(
      child: Container(
        width: 280,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.05),
          border: Border(
            right: BorderSide(color: Colors.white.withOpacity(0.1)),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 30),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  Icon(Icons.bar_chart, color: _primaryColor, size: 28),
                  const SizedBox(width: 10),
                  Text(
                    'تقارير اليوزرمانجر',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 30),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // قسم الإدارة الرئيسية
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 8,
                      ),
                      child: Text(
                        'الإدارة الرئيسية',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: Colors.white.withOpacity(0.5),
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    _buildNavItem(
                      icon: Icons.dashboard,
                      title: 'لوحة التحكم',
                      isActive: false,
                      onTap: () {
                        Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                            builder:
                                (context) =>
                                    RouterDetailsPage(client: widget.client),
                          ),
                        );
                      },
                    ),

                    // قسم الهوتسبوت (قابل للطي)
                    _buildExpandableSection(
                      title: 'إدارة الهوتسبوت',
                      icon: Icons.wifi,
                      initiallyExpanded: isHotspotExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isHotspotExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.people,
                          title: 'قائمة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        UsersPage(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.speed,
                          title: 'البروفايل',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        HotspotProfile(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.person_add,
                          title: 'اضافة مستخدم',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 0,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.group_add,
                          title: 'اضافة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 1,
                                    ),
                              ),
                            );
                          },
                        ),
                      ],
                    ),

                    // قسم اليوزر مانجر (قابل للطي)
                    _buildExpandableSection(
                      title: 'إدارة اليوزر مانجر',
                      icon: Icons.manage_accounts,
                      initiallyExpanded: isUserManagerExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isUserManagerExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.people_outline,
                          title: 'قائمة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => UserManagerUserList(
                                      client: widget.client,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.speed,
                          title: 'البروفايل',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => UserManagerProfile(
                                      client: widget.client,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.payment_rounded,
                          title: 'اضافة مستخدم',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => AddUserManagerCards(
                                      client: widget.client,
                                      initialTab: 0,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.credit_score,
                          title: 'اضافة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => AddUserManagerCards(
                                      client: widget.client,
                                      initialTab: 1,
                                    ),
                              ),
                            );
                          },
                        ),

                        _buildNavItem(
                          icon: Icons.assignment,
                          title: 'السجلات',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => UserManagerSession(
                                      client: widget.client,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.bar_chart,
                          title: 'التقارير',
                          isActive: true,
                          onTap: () {
                            // Navigation code here
                          },
                        ),
                      ],
                    ),

                    // قسم الإعدادات والأدوات (قابل للطي)
                    _buildExpandableSection(
                      title: 'الإعدادات والأدوات',
                      icon: Icons.settings,
                      initiallyExpanded: isSettingsExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isSettingsExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.settings,
                          title: 'قبل الطباعة والأمان',
                          isActive: false,
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        FreeRebuildDB(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.backup,
                          title: 'النسخ الاحتياطي',
                          isActive: false,
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        backupSN(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.devices_other_outlined,
                          title: 'قطع البث',
                          isActive: false,
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        Transmitters(client: widget.client),
                              ),
                            );
                          },
                        ),
                      ],
                    ),

                    // قسم المساعدة والدعم (قابل للطي)
                    _buildExpandableSection(
                      title: 'المساعدة والدعم',
                      icon: Icons.help,
                      initiallyExpanded: isHelpExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isHelpExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.help_outline,
                          title: 'مركز المساعدة',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder: (_) => HelpDesk(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.feedback,
                          title: 'إرسال ملاحظات',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => SendNotes(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.info_outline,
                          title: 'حول التطبيق',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder: (_) => AboutApp(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.logout,
                          title: 'تسجيل الخروج',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(builder: (context) => Login()),
                            );
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildNavItem({
    required IconData icon,
    required String title,
    required bool isActive,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 4),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: isActive ? _primaryColor.withOpacity(0.2) : Colors.transparent,
          borderRadius: BorderRadius.circular(8),
          border:
              isActive
                  ? Border.all(color: _primaryColor.withOpacity(0.5), width: 1)
                  : null,
        ),
        child: Row(
          children: [
            Icon(
              icon,
              color: isActive ? _primaryColor : Colors.white.withOpacity(0.7),
              size: 24,
            ),
            const SizedBox(width: 12),
            Text(
              title,
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: isActive ? Colors.white : Colors.white.withOpacity(0.7),
                fontSize: 16,
                fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
              ),
            ),
            if (isActive) const Spacer(),
            if (isActive)
              Container(
                width: 8,
                height: 8,
                decoration: BoxDecoration(
                  color: _primaryColor,
                  shape: BoxShape.circle,
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildExpandableSection({
    required String title,
    required IconData icon,
    required List<Widget> children,
    required bool initiallyExpanded,
    required ValueChanged<bool> onExpansionChanged,
  }) {
    return ExpansionTile(
      title: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          children: [
            Icon(icon, color: Colors.white.withOpacity(0.7), size: 24),
            const SizedBox(width: 12),
            Text(
              title,
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: Colors.white.withOpacity(0.7),
                fontSize: 16,
                fontWeight: FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
      childrenPadding: const EdgeInsets.only(left: 16),
      collapsedIconColor: Colors.white.withOpacity(0.7),
      iconColor: Colors.white.withOpacity(0.7),
      initiallyExpanded: initiallyExpanded,
      onExpansionChanged: onExpansionChanged,
      children: children,
    );
  }

  Widget _buildUniversalDrawer() {
    return Drawer(
      backgroundColor: _backgroundColor,
      child: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              // Stylish Drawer Header
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 25,
                ),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      _primaryColor.withOpacity(0.9),
                      _primaryColor.withOpacity(0.6),
                    ],
                    begin: Alignment.topRight,
                    end: Alignment.bottomLeft,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      blurRadius: 6,
                      offset: Offset(0, 3),
                    ),
                  ],
                  borderRadius: BorderRadius.vertical(
                    bottom: Radius.circular(24),
                  ),
                ),
                child: Row(
                  children: [
                    // Logo or Icon Container
                    Container(
                      width: 60,
                      height: 60,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.white.withOpacity(0.1),
                        border: Border.all(color: Colors.white24, width: 1),
                      ),
                      child: Icon(
                        Icons.network_check,
                        color: Colors.white,
                        size: 30,
                      ),
                    ),
                    const SizedBox(width: 16),
                    // App Title & Subtitle
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Micro Panel',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: Colors.white,
                              fontSize: 22,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'لوحة تحكم الشبكة الذكية',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: Colors.white70,
                              fontSize: 14,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              // Main Navigation Items
              _buildUniversalDrawerItem(
                icon: Icons.dashboard,
                title: 'لوحة التحكم',
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    PageRouteBuilder(
                      pageBuilder:
                          (context, animation, secondaryAnimation) =>
                              RouterDetailsPage(client: widget.client),
                      transitionsBuilder: (
                        context,
                        animation,
                        secondaryAnimation,
                        child,
                      ) {
                        const begin = Offset(0.0, 1.0);
                        const end = Offset.zero;
                        const curve = Curves.ease;
                        var tween = Tween(
                          begin: begin,
                          end: end,
                        ).chain(CurveTween(curve: curve));
                        return SlideTransition(
                          position: animation.drive(tween),
                          child: child,
                        );
                      },
                      transitionDuration: const Duration(milliseconds: 300),
                    ),
                  );
                },
              ),

              // Hotspot Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(Icons.wifi, color: Colors.white.withOpacity(0.7)),
                    const SizedBox(width: 12),
                    Text(
                      'إدارة الهوتسبوت',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                children: [
                  _buildUniversalDrawerItem(
                    icon: Icons.people,
                    title: 'قائمة المستخدمين',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  UsersPage(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.speed,
                    title: 'البروفايل',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  HotspotProfile(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.person_add,
                    title: 'إضافة مستخدم',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AddHotspotCardsPage(
                                    client: widget.client,
                                    initialTab: 0,
                                  ),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.group_add,
                    title: 'إضافة مستخدمين',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AddHotspotCardsPage(
                                    client: widget.client,
                                    initialTab: 1,
                                  ),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                ],
              ),

              // User Manager Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(
                      Icons.manage_accounts,
                      color: Colors.white.withOpacity(0.7),
                    ),
                    const SizedBox(width: 12),
                    Text(
                      'إدارة اليوزر مانجر',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                initiallyExpanded: true,
                children: [
                  _buildUniversalDrawerItem(
                    icon: Icons.people_outline,
                    title: 'قائمة المستخدمين',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  UserManagerUserList(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.speed,
                    title: 'البروفايل',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  UserManagerProfile(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.payment_rounded,
                    title: 'إضافة مستخدم',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AddUserManagerCards(
                                    client: widget.client,
                                    initialTab: 0,
                                  ),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.credit_score,
                    title: 'إضافة مستخدمين',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AddUserManagerCards(
                                    client: widget.client,
                                    initialTab: 1,
                                  ),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.assignment,
                    title: 'السجلات',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  UserManagerSession(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.bar_chart,
                    title: 'التقارير',
                    isActive: true,
                    onTap: () {},
                  ),
                ],
              ),

              // Settings Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(Icons.settings, color: Colors.white.withOpacity(0.7)),
                    const SizedBox(width: 12),
                    Text(
                      'الإعدادات والأدوات',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                children: [
                  _buildUniversalDrawerItem(
                    icon: Icons.settings,
                    title: 'قبل الطباعة والأمان',
                    onTap: () {
                      Navigator.push(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  FreeRebuildDB(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.backup,
                    title: 'النسخ الاحتياطي',
                    onTap: () {
                      Navigator.push(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  backupSN(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.devices_other_outlined,
                    title: 'قطع البث',
                    onTap: () {
                      Navigator.push(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  Transmitters(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                ],
              ),

              // Help Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(Icons.help, color: Colors.white.withOpacity(0.7)),
                    const SizedBox(width: 12),
                    Text(
                      'المساعدة والدعم',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                children: [
                  _buildUniversalDrawerItem(
                    icon: Icons.help_outline,
                    title: 'مركز المساعدة',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  HelpDesk(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.feedback,
                    title: 'إرسال ملاحظات',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  SendNotes(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.info_outline,
                    title: 'حول التطبيق',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AboutApp(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                ],
              ),

              const Divider(color: Colors.white24),

              // Logout Item
              _buildUniversalDrawerItem(
                icon: Icons.logout,
                title: 'تسجيل خروج',
                color: Colors.red,
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    PageRouteBuilder(
                      pageBuilder:
                          (context, animation, secondaryAnimation) => Login(),
                      transitionsBuilder: (
                        context,
                        animation,
                        secondaryAnimation,
                        child,
                      ) {
                        const begin = Offset(0.0, 1.0);
                        const end = Offset.zero;
                        const curve = Curves.ease;
                        var tween = Tween(
                          begin: begin,
                          end: end,
                        ).chain(CurveTween(curve: curve));
                        return SlideTransition(
                          position: animation.drive(tween),
                          child: child,
                        );
                      },
                      transitionDuration: const Duration(milliseconds: 300),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildUniversalDrawerItem({
    required IconData icon,
    required String title,
    Color color = Colors.white,
    required VoidCallback onTap,
    bool isActive = false,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
      decoration: BoxDecoration(
        color: isActive ? _primaryColor.withOpacity(0.1) : Colors.transparent,
        borderRadius: BorderRadius.circular(8),
        border:
            isActive
                ? Border.all(color: _primaryColor.withOpacity(0.5), width: 1)
                : null,
      ),
      child: ListTile(
        leading: Icon(icon, color: isActive ? _primaryColor : color),
        title: Text(
          title,
          style: TextStyle(
            fontFamily: 'Tajawal',
            color: isActive ? _primaryColor : color,
            fontSize: 14,
            fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
          ),
        ),
        onTap: onTap,
        contentPadding: const EdgeInsets.symmetric(horizontal: 16),
      ),
    );
  }

  Widget _buildDrawerItem({
    required IconData icon,
    required String title,
    Color color = Colors.white,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(icon, color: color),
      title: Text(title, style: TextStyle(fontFamily: 'Tajawal', color: color)),
      onTap: onTap,
    );
  }

  Widget _AppBarActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onPressed,
    required Color color,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 4),
      child: Tooltip(
        message: label,
        child: IconButton(
          icon: Icon(icon, size: 20),
          color: color,
          onPressed: onPressed,
          style: IconButton.styleFrom(
            backgroundColor: color.withOpacity(0.1),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            padding: EdgeInsets.all(8),
          ),
        ),
      ),
    );
  }

  Widget _buildMainContent({bool showHeader = true}) {
    final userCount = _filteredSessions.length;
    final totalPrice = _filteredSessions.fold(0, (sum, user) {
      final price = int.tryParse(user['price']?.toString() ?? '0') ?? 0;
      return sum + (price ~/ 100);
    });

    return Stack(
      children: [
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                _backgroundColor.withOpacity(0.9),
                _backgroundColor.withOpacity(0.7),
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
          ),
          child: Column(
            children: [
              if (showHeader)
                Container(
                  height: 60,
                  padding: EdgeInsets.symmetric(horizontal: 8),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.05),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: Icon(Icons.menu, color: _textColor),
                        onPressed: () {},
                        padding: EdgeInsets.zero,
                      ),
                      Expanded(
                        child: Text(
                          'تقارير اليوزرمانجر',
                          style: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor,
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      if (userCount > 0)
                        Row(
                          children: [
                            Container(
                              padding: EdgeInsets.all(12),
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(12),
                                border: Border.all(color: Colors.white24),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.people,
                                    color: Colors.white70,
                                    size: 20,
                                  ),
                                  SizedBox(width: 6),
                                  Text(
                                    'عدد المستخدمين: $userCount',
                                    style: TextStyle(
                                      fontFamily: 'Tajawal',
                                      color: Colors.white,
                                      fontSize: 15,
                                    ),
                                  ),
                                  SizedBox(width: 16),
                                  Icon(
                                    Icons.attach_money,
                                    color: Colors.greenAccent,
                                    size: 20,
                                  ),
                                  SizedBox(width: 6),
                                  Text(
                                    'الإجمالي: $totalPrice',
                                    style: TextStyle(
                                      fontFamily: 'Tajawal',
                                      color: Colors.greenAccent,
                                      fontSize: 15,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(width: 8),
                            IconButton(
                              icon: Icon(
                                Icons.picture_as_pdf,
                                color: _primaryColor,
                              ),
                              onPressed:
                                  _filteredSessions.isNotEmpty
                                      ? _generatePdf
                                      : null,
                              tooltip: 'تصدير إلى PDF',
                            ),
                          ],
                        ),
                    ],
                  ),
                ),

              Padding(
                padding: const EdgeInsets.all(16.0),
                child: _buildDateRangeSelector(),
              ),

              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: _buildDataTable(),
                ),
              ),
            ],
          ),
        ),

        ValueListenableBuilder<bool>(
          valueListenable: _isLoadingNotifier,
          builder: (context, isLoading, child) {
            return isLoading
                ? Container(
                  color: Colors.black.withOpacity(0.5),
                  child: Center(
                    child: Container(
                      padding: EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        color: _cardColor.withOpacity(0.9),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          CircularProgressIndicator(color: _primaryColor),
                          SizedBox(height: 16),
                          Text(
                            'جاري اعداد التقارير ...',
                            style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Tajawal',
                              fontSize: 16,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                )
                : SizedBox.shrink();
          },
        ),
      ],
    );
  }
}

class MicroPanelSales {
  final RouterOSClient client;
  Socket? socket;

  MicroPanelSales({required this.client});

  String get host => client.address;
  int get port => client.port ?? 8728;
  String get user => client.user;
  String get pass => client.password;
  final _recvBuffer = <int>[];

  Future<void> connect() async {
    try {
      socket = await Socket.connect(host, port, timeout: Duration(seconds: 10));

      // الاستماع إلى البيانات الواردة
      socket!.listen(
        (data) {
          _recvBuffer.addAll(data);
        },
        onError: (error) {
          print('Socket error: $error');
          disconnect();
        },
        onDone: () {
          print('Socket connection closed by router');
          disconnect();
        },
      );

      // إرسال بيانات تسجيل الدخول
      await _sendLogin();
    } catch (e) {
      throw Exception('فشل الاتصال: $e');
    }
  }

  Future<void> _sendLogin() async {
    if (socket == null) return;

    // إرسال اسم المستخدم
    await sendSentence(['/login', '=name=$user', '=password=$pass']);

    // قراءة الرد
    final response = await _readResponse();
    if (response.isEmpty || !response.any((s) => s.contains('!done'))) {
      throw Exception('فشل المصادقة');
    }
  }

  Future<void> sendSentence(List<String> words) async {
    if (socket == null) return;

    final buffer = _encodeSentence(words);
    socket!.add(buffer);
    await socket!.flush();
  }

  List<int> _encodeSentence(List<String> words) {
    final buffer = <int>[];
    for (final word in words) {
      final wordBytes = utf8.encode(word);
      final len = wordBytes.length;

      if (len < 0x80) {
        buffer.add(len);
      } else if (len < 0x4000) {
        buffer.add((len >> 8) | 0x80);
        buffer.add(len & 0xFF);
      } else if (len < 0x200000) {
        buffer.add((len >> 16) | 0xC0);
        buffer.add((len >> 8) & 0xFF);
        buffer.add(len & 0xFF);
      } else {
        buffer.add((len >> 24) | 0xE0);
        buffer.add((len >> 16) & 0xFF);
        buffer.add((len >> 8) & 0xFF);
        buffer.add(len & 0xFF);
      }

      buffer.addAll(wordBytes);
    }
    buffer.add(0); // نهاية الجملة
    return buffer;
  }

  Future<List<String>> _readResponse() async {
    if (socket == null) return [];

    final sentences = await _readSentences();
    return sentences.expand((s) => s).toList();
  }

  void disconnect() {
    socket?.close();
    socket = null;
  }

  Future<List<List<String>>> _readSentences() async {
    final sentences = <List<String>>[];
    while (true) {
      await Future.delayed(Duration(milliseconds: 100));

      if (_recvBuffer.isEmpty) continue;

      final buf = List<int>.from(_recvBuffer);
      try {
        var i = 0;
        while (i < buf.length) {
          final sentence = <String>[];
          while (i < buf.length && buf[i] != 0) {
            int len = buf[i++];
            int bytesCount = 1;

            if (len & 0x80 != 0) {
              bytesCount =
                  (len & 0xC0) == 0x80
                      ? 2
                      : (len & 0xE0) == 0xC0
                      ? 3
                      : 4;
              len = ((len & 0x7F) << ((bytesCount - 1) * 8));

              for (int j = 0; j < bytesCount - 1 && i < buf.length; j++) {
                len |= buf[i++] << ((bytesCount - 2 - j) * 8);
              }
            }

            if (i + len > buf.length) {
              i -= bytesCount;
              break;
            }

            sentence.add(utf8.decode(buf.sublist(i, i + len)));
            i += len;
          }

          if (i < buf.length && buf[i] == 0) {
            i++; // تخطي حرف الإنهاء
            sentences.add(sentence);

            // إذا كانت الجملة تحتوي على !done، نخرج
            if (sentence.isNotEmpty && sentence.first == '!done') {
              _recvBuffer.removeRange(0, i);
              return sentences;
            }
          } else {
            break; // بيانات غير مكتملة
          }
        }

        _recvBuffer.removeRange(0, i);

        // إذا وجدنا جملة !done نعود بالنتيجة
        if (sentences.any((s) => s.isNotEmpty && s.first == '!done')) {
          return sentences;
        }
      } catch (e) {
        print('Error parsing sentences');
        break;
      }
    }
    return sentences;
  }
}


ملاحظة اعطيني الجزء السابق والجزء المراد استبدالة بة