اريد ان يكون حقول اختيار الوقت والتاريخ لها قيم افتراضية على سبيل المثال في من تاريخ اريد ان يكون قبل تاريخ اليوم بيوم واحد اما في الى تاريخ اريد ان يكون تاريخ اليوم وكذلك المن وقت اريد ان  يكون بداية اليوم
اما في الى تاريخ اريد ان يكون الوقت الحالي
للعلم الكود
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';

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();
    _MicroPanelSales = MicroPanelSales(client: widget.client);
    _connectAndFetchData();
  }

  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 {
    try {
      _isLoadingNotifier.value = true;
      _errorNotifier.value = null;
      print('بدء محاولة الجلب');

      // جلب قائمة المستخدمين
      await _MicroPanelSales.sendSentence([
        '/tool/user-manager/user/print',
        '?download-used',
        '=.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} مستخدم');

      List<Map<String, dynamic>> paymentDataList = [];
      List<Map<String, dynamic>> sessionDataList = [];

      // جلب بيانات الدفع والجلسات لكل مستخدم
      for (var user in userList) {
        final username = user['username'];
        if (username == null) continue;

        try {
          // جلب بيانات الدفع
          await _MicroPanelSales.sendSentence([
            '/tool/user-manager/payment/print',
            '?user=$username',
            '=.proplist=price,time',
          ]);
          final paymentResponse = await _MicroPanelSales._readSentences();

          for (var sentence in paymentResponse) {
            if (sentence.isNotEmpty && sentence.first == '!re') {
              Map<String, dynamic> paymentData = {'username': username};
              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) {
                paymentDataList.add(paymentData);
              }
            }
          }

          // جلب بيانات الجلسات
          await _MicroPanelSales.sendSentence([
            '/tool/user-manager/session/print',
            '?user=$username',
            '=.proplist=nas-port-id,from-time',
          ]);
          final sessionResponse = await _MicroPanelSales._readSentences();

          for (var sentence in sessionResponse) {
            if (sentence.isNotEmpty && sentence.first == '!re') {
              Map<String, dynamic> sessionData = {'username': username};
              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) {
                sessionDataList.add(sessionData);
                break; // نأخذ أول جلسة فقط
              }
            }
          }
        } catch (e) {
          debugPrint('Error fetching data for user $username: $e');
        }
      }

      // تخزين جميع البيانات بدون تصفية
      _allSessions =
          userList.map((user) {
            final username = user['username'];
            final payments =
                paymentDataList
                    .where((p) => p['username'] == username)
                    .toList();
            final sessions =
                sessionDataList
                    .where((s) => s['username'] == username)
                    .toList();

            return {
              'username': username,
              'price': payments.isNotEmpty ? payments.last['price'] : '0',
              'from-time':
                  sessions.isNotEmpty
                      ? sessions.first['from-time']
                      : 'غير معروف',
              'nas-port-id':
                  sessions.isNotEmpty
                      ? sessions.first['nas-port-id']
                      : 'غير معروف',
              'parsed-time':
                  sessions.isNotEmpty
                      ? _parseMikrotikDateTime(sessions.first['from-time'])
                      : null,
            };
          }).toList();

      // لا نقوم بتعيين _filteredSessions هنا، بل ننتظر حتى يحدد المستخدم الفترة الزمنية
      if (mounted) {
        setState(() {
          _filteredSessions = [];
        });
      }

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

  // دالة لتصفية البيانات حسب الفترة الزمنية
  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(),
              ),
        ),
      ),
      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); // القسمة على 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)
                        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,
                                ),
                              ),
                            ],
                          ),
                        ),
                    ],
                  ),
                ),

              // <-- هنا أضفنا اختيار الفترة الزمنية -->
              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;
  }
}


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