اريد اضافة ايقونة في حال قام المستخدم بالنقر عليها يبقى اشعار ال local notification ظاهر ويتحدث بياناتة كل ثانية ويكون موجود في ال notification panel بدلاً من طريقة الاظهار العادية
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:http/http.dart' as http;
import 'package:hotspot/dashboard.dart';
import 'package:iconsax/iconsax.dart'; // حزمة الأيقونات الاحترافية

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Mikro Hotspot',
      debugShowCheckedModeBanner: false,

      // دعم اللغة العربية
      locale: const Locale('ar'),
      supportedLocales: const [Locale('ar')],
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],

      theme: ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'Tajawal',
        scaffoldBackgroundColor: Colors.grey[50],
        appBarTheme: AppBarTheme(
          elevation: 0,
          centerTitle: true,
          backgroundColor: Colors.white,
          iconTheme: const IconThemeData(color: Colors.black87),
          titleTextStyle: TextStyle(
            color: Colors.grey[800],
            fontSize: 20,
            fontWeight: FontWeight.bold,
            fontFamily: 'Tajawal',
          ),
        ),
      ),
      home: const SplashScreen(),
    );
  }
}

class CookieManager {
  final Map<String, String> cookies = {};

  void updateCookies(http.Response response) {
    final setCookieHeaders = response.headers.entries
        .where((entry) => entry.key.toLowerCase() == 'set-cookie')
        .map((entry) => entry.value);

    for (var header in setCookieHeaders) {
      final cookiesParts = header.split(',');
      for (var cookiePart in cookiesParts) {
        final cookie = cookiePart.split(';')[0];
        final cookiePair = cookie.split('=');
        if (cookiePair.length == 2) {
          cookies[cookiePair[0].trim()] = cookiePair[1].trim();
        }
      }
    }
  }

  String get cookieHeader {
    return cookies.entries.map((e) => '${e.key}=${e.value}').join('; ');
  }

  void clear() {
    cookies.clear();
  }
}

class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1400),
    );
    _animation = CurvedAnimation(parent: _controller, curve: Curves.easeInOut);
    _controller.repeat(reverse: true);

    Timer(const Duration(seconds: 3), () {
      // تحقّق أن الويجيت ما زال موجودًا قبل التنقل
      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => const AuthCheckScreen()),
        );
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF1565C0),
      body: Center(
        child: FadeTransition(
          opacity: _animation,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Iconsax.wifi, size: 120, color: Colors.white),
              const SizedBox(height: 20),
              const Text(
                'شبكة سكاي نت',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  color: Colors.white,
                  fontSize: 26,
                  fontWeight: FontWeight.bold,
                  letterSpacing: 1.3,
                ),
              ),
              const SizedBox(height: 40),
              SpinKitFadingCircle(color: Colors.white, size: 50.0),
            ],
          ),
        ),
      ),
    );
  }
}

class AuthCheckScreen extends StatefulWidget {
  const AuthCheckScreen({Key? key}) : super(key: key);

  @override
  State<AuthCheckScreen> createState() => _AuthCheckScreenState();
}

class _AuthCheckScreenState extends State<AuthCheckScreen> {
  bool _checking = true;
  final CookieManager _cookieManager = CookieManager();

  Future<Map<String, dynamic>> _fetchUserData() async {
    try {
      final response = await http
          .get(Uri.parse('http://172.16.0.1/status?var=json'))
          .timeout(const Duration(seconds: 10));

      _cookieManager.updateCookies(response);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        if (data.containsKey('errors')) {
          return {'error': data['errors'].toString()};
        }
        return Map<String, dynamic>.from(data);
      } else {
        return {'error': 'خطأ في استجابة الراوتر: ${response.statusCode}'};
      }
    } catch (e) {
      return {'error': 'تعذر الاتصال بالراوتر: ${e.toString()}'};
    }
  }

  @override
  void initState() {
    super.initState();
    _checkLogin();
  }

  Future<void> _checkLogin() async {
    final data = await _fetchUserData();

    if (data.containsKey('error')) {
      if (mounted) {
        setState(() {
          _checking = false;
        });
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => const LoginScreen()),
        );
      }
      return;
    }

    final loggedIn = data['logged_in'] ?? 'no';

    if (loggedIn == 'yes' || loggedIn == 'on') {
      if (mounted) {
        final username = data['username'] ?? 'مستخدم';

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (_) => DashboardScreen(username: username),
          ),
        );
      }
    } else {
      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => const LoginScreen()),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:
            _checking
                ? Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SpinKitCircle(
                      color: Theme.of(context).primaryColor,
                      size: 60,
                    ),
                    const SizedBox(height: 20),
                    Text(
                      'جارِ التحقق من حالة تسجيل الدخول...',
                      style: TextStyle(color: Colors.grey[700], fontSize: 16),
                    ),
                  ],
                )
                : const SizedBox(),
      ),
    );
  }
}

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController _usernameController = TextEditingController();
  bool _isLoading = false;
  String _message = '';
  bool _showMessage = false;
  bool _isError = false;
  final CookieManager _cookieManager = CookieManager();

  void _showStatusMessage(String message, {bool isError = false}) {
    setState(() {
      _message = message;
      _showMessage = true;
      _isError = isError;
    });
    Future.delayed(const Duration(seconds: 4), () {
      if (mounted) setState(() => _showMessage = false);
    });
  }

  Future<void> _login() async {
    if (_usernameController.text.isEmpty) {
      _showStatusMessage('يجب إدخال اسم المستخدم', isError: true);
      return;
    }

    setState(() {
      _isLoading = true;
      _showMessage = false;
      _cookieManager.clear();
    });

    try {
      // طلب Get لترقية الكوكيز أولاً
      final responseGet = await http
          .get(Uri.parse('http://172.16.0.1/status?var=json'))
          .timeout(const Duration(seconds: 10));
      _cookieManager.updateCookies(responseGet);

      // طلب تسجيل الدخول
      final loginResponse = await http
          .post(
            Uri.parse('http://172.16.0.1/login'),
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Cookie': _cookieManager.cookieHeader,
            },
            body: {'username': _usernameController.text, 'password': ''},
          )
          .timeout(const Duration(seconds: 10));
      _cookieManager.updateCookies(loginResponse);

      // طلب Get بعد تسجيل الدخول للتحقق من الحالة
      final responseAfterLogin = await http
          .get(
            Uri.parse('http://172.16.0.1/status?var=json'),
            headers: {'Cookie': _cookieManager.cookieHeader},
          )
          .timeout(const Duration(seconds: 10));

      final data = json.decode(responseAfterLogin.body);

      final loggedInStatus = data['logged_in'] ?? 'no';

      if (loggedInStatus == 'yes' || loggedInStatus == 'on') {
        _showStatusMessage('تم تسجيل الدخول بنجاح', isError: false);
        if (mounted) {
          final username = data['username'] ?? _usernameController.text;
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => DashboardScreen(username: username),
            ),
          );
        }
      } else {
        _showStatusMessage(
          'فشل تسجيل الدخول. تأكد من صحة البيانات.',
          isError: true,
        );
      }
    } catch (e) {
      _showStatusMessage('حدث خطأ: ${e.toString()}', isError: true);
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('تسجيل الدخول'), elevation: 0),
      body: Stack(
        children: [
          SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 40),
            child: Column(
              children: [
                const SizedBox(height: 40),
                Icon(
                  Iconsax.wifi,
                  size: 100,
                  color: Theme.of(context).primaryColor,
                ),
                const SizedBox(height: 30),
                Text(
                  'مرحباً بك في شبكة سكاي نت',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'Tajawal',
                    color: Colors.grey[800],
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 10),
                Text(
                  'الرجاء إدخال بيانات الدخول للاتصال بالشبكة',
                  style: TextStyle(fontSize: 16, color: Colors.grey[600]),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 40),
                Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.1),
                        spreadRadius: 3,
                        blurRadius: 10,
                        offset: const Offset(0, 3),
                      ),
                    ],
                  ),
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    children: [
                      TextField(
                        controller: _usernameController,
                        decoration: InputDecoration(
                          labelText: 'اسم المستخدم',
                          prefixIcon: const Icon(Iconsax.user),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          contentPadding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                        ),
                        style: const TextStyle(fontSize: 16),
                      ),
                      const SizedBox(height: 30),
                      SizedBox(
                        width: double.infinity,
                        height: 50,
                        child: ElevatedButton(
                          onPressed: _isLoading ? null : _login,
                          style: ElevatedButton.styleFrom(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10),
                            ),
                            elevation: 0,
                          ),
                          child:
                              _isLoading
                                  ? const SizedBox(
                                    width: 24,
                                    height: 24,
                                    child: CircularProgressIndicator(
                                      color: Colors.white,
                                      strokeWidth: 3,
                                    ),
                                  )
                                  : const Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text('تسجيل الدخول'),
                                      SizedBox(width: 10),
                                      Icon(Iconsax.login, size: 20),
                                    ],
                                  ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          if (_showMessage)
            Positioned(
              bottom: 20,
              left: 20,
              right: 20,
              child: AnimatedOpacity(
                opacity: _showMessage ? 1 : 0,
                duration: const Duration(milliseconds: 300),
                child: Material(
                  elevation: 6,
                  borderRadius: BorderRadius.circular(12),
                  color: _isError ? Colors.red[50] : Colors.green[50],
                  child: Container(
                    padding: const EdgeInsets.all(16),
                    child: Row(
                      children: [
                        Icon(
                          _isError ? Iconsax.close_circle : Iconsax.tick_circle,
                          color: _isError ? Colors.red : Colors.green,
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            _message,
                            style: TextStyle(
                              color:
                                  _isError
                                      ? Colors.red[800]
                                      : Colors.green[800],
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        IconButton(
                          onPressed: () => setState(() => _showMessage = false),
                          icon: const Icon(Icons.close),
                          color: _isError ? Colors.red : Colors.green,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}