import 'dart:math'; import 'dart:convert'; import 'package:go_router/go_router.dart'; import 'package:http/http.dart' as http; import 'package:flutter/material.dart'; import 'package:pocketbase/pocketbase.dart'; import 'package:uae_stat/config/api_config.dart'; import 'otp_verification.dart'; class Changepassword extends StatefulWidget { // final String email; final String userId; const Changepassword({Key? key, required this.userId}); @override State createState() => _ResetPasswordScreenState(); } class _ResetPasswordScreenState extends State { final _pb = PocketBase(apiUrl); // final pb = PocketBase('http://127.0.0.1:8090'); final _formKey = GlobalKey(); final _emailController = TextEditingController(); bool _isLoading = false; String? _otpId; String? _verificationCode; Future sendVerificationCode(String email) async { if (_formKey.currentState!.validate()) { setState(() { _isLoading = true; }); final email = _emailController.text.trim(); //print('Email - $email'); try { // Authenticate admin to get the token final adminAuth = await _pb.admins .authWithPassword('pb@venbainfotech.com', 'pb@venbainfotech.com'); final authToken = adminAuth.token; //print('Admin Token: $authToken'); // Check if email exists in the user collection final userCheckResponse = await http.get( Uri.parse( '$apiUrl/api/collections/users/records?filter=email="$email"'), headers: { 'Authorization': 'Bearer $authToken', }, ); if (userCheckResponse.statusCode == 200) { final userData = jsonDecode(userCheckResponse.body); //print('userDetails ->: $userData'); if (userData['items'].isNotEmpty) { // Email exists; retrieve user ID // final userId = userData['items'][0]['id']; // Proceed with OTP request final otpResponse = await http.post( Uri.parse('$apiUrl/api/collections/otp_requests/records'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $authToken', }, body: jsonEncode({ 'email': email, }), ); if (otpResponse.statusCode == 200) { //print('otpResponse- ${otpResponse.body} '); final otpData = jsonDecode(otpResponse.body); final otp = otpData['otp']; // OTP value from the response final otpId = otpData['id']; _otpId = otpData['id']; //print('OTP: $otp, ID: $otpId, '); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text("Verification code sent to $email")), ); // Navigate to the Email Verification screen context.go( '/mailverification', extra: { 'email': email, 'userId': widget.userId, // Pass user ID to the next screen 'otp': otp, 'otpId': otpId, 'sendVerificationCode': sendVerificationCode, }, ); } else { final error = jsonDecode(otpResponse.body)['error'] ?? "Unknown error"; ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text("Error: $error")), ); } } else { // Email not found ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text("Please Enter Registered Mail ID")), ); } } else { // Error in user collection request final error = jsonDecode(userCheckResponse.body)['error'] ?? "Unknown error"; ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text("Error: $error")), ); } } catch (e) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text("Failed to process request: $e")), ); } finally { setState(() { _isLoading = false; }); } } } @override void initState() { super.initState(); print(widget.userId); } @override void dispose() { _emailController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { double screenheight = MediaQuery.of(context).size.height; double screenwidth = MediaQuery.of(context).size.width; return Scaffold( backgroundColor: Colors.white, body: SingleChildScrollView( child: SafeArea( child: Padding( padding: const EdgeInsets.all(24.0), child: Form( key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Center( child: const Text( 'Reset Password', style: TextStyle( fontSize: 40, fontWeight: FontWeight.w300, color: Colors.black87, ), ), ), const SizedBox(height: 8), Center( child: const Text( 'Please Enter Your Email Address To\nReceive a verification Code', style: TextStyle( fontSize: 14, color: Colors.black87, fontWeight: FontWeight.w400, height: 1.5, ), ), ), const SizedBox(height: 24), TextFormField( controller: _emailController, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( hintText: 'Enter your email', hintStyle: const TextStyle( color: Color(0xFFC3C6CB), fontSize: 14, ), prefixIcon: const Icon( Icons.email_outlined, color: Colors.blue, size: 20, ), filled: true, fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Colors.black12, width: 1, ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Colors.black12, width: 1, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFF8B7355), width: 1, ), ), contentPadding: const EdgeInsets.symmetric( horizontal: 16, vertical: 14, ), ), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your email'; } if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$') .hasMatch(value)) { return 'Please enter a valid email'; } return null; }, ), const SizedBox(height: 24), SizedBox( width: double.infinity, height: 48, child: ElevatedButton( onPressed: _isLoading ? null : () { final email = _emailController.text.trim(); sendVerificationCode(email); }, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF8B7355), foregroundColor: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), elevation: 0, ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_isLoading) Container( child: const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ), ) else ...[ const Text( 'Send', style: TextStyle( fontSize: 16, fontWeight: FontWeight.w500, ), ), SizedBox( width: 2, ), Icon( Icons.arrow_forward_ios, color: Colors.white38, size: 18, ), ], ], ), ), ), ], ), SizedBox( height: screenheight / 3, ), Center( child: Container( height: screenheight / 8, width: screenwidth / 2, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( "assets/splash_screen/logo.png"), // Background image asset fit: BoxFit.fill, ), ), )) ], ), ), ), ), ), ); } }