You are on page 1of 6

import 'package:cloud_firestore/cloud_firestore.

dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:helloworld/crop_summary.dart';
import 'package:helloworld/newpage.dart';

import 'auth.dart';

class ApplicationOldCropPage extends StatefulWidget {


final Auth auth = Auth();
final String organicInputId;

ApplicationOldCropPage({required this.organicInputId});

@override
_ApplicationOldCropPageState createState() => _ApplicationOldCropPageState();
}

class _ApplicationOldCropPageState extends State<ApplicationOldCropPage> {


bool isNewCrop = false;
final TextEditingController cropController = TextEditingController();
final TextEditingController amountController = TextEditingController();
String organicInputName = '';
late Future<int> _totalAmountUsedFuture;

@override
void initState() {
super.initState();
_getOrganicInputName(widget.organicInputId);
_totalAmountUsedFuture = _fetchTotalAmountUsed(widget.organicInputId);
}

void _getOrganicInputName(String organicInputId) async {


try {
var organicInputDoc = await FirebaseFirestore.instance
.collection('organic_inputs')
.doc(organicInputId)
.get();

setState(() {
organicInputName = organicInputDoc['name'] ?? '';
});
} catch (e) {
print('Error fetching organic input name: $e');
setState(() {
organicInputName = 'Unknown Organic Input';
});
}
}

Future<int> _fetchTotalAmountUsed(String documentId) async {


try {
int totalAmountUsed = 0;
QuerySnapshot applicationsSnapshot = await FirebaseFirestore.instance
.collection('applications')
.where('organicInputId', isEqualTo: documentId)
.get();
for (QueryDocumentSnapshot doc in applicationsSnapshot.docs) {
int amount = doc['amount'] as int; // Convert to int
totalAmountUsed += amount;
}
return totalAmountUsed;
} catch (e) {
print('Error fetching total amount used: $e');
return 0;
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.green[600],
title: Text('Application Page'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
children: [
Text('New Crop'),
Switch(
value: isNewCrop,
onChanged: (value) {
setState(() {
isNewCrop = value;
});
},
),
],
),
SizedBox(height: 20),
isNewCrop ? _buildNewCropForm() : _buildExistingCropsDropdown(),
isNewCrop ? SizedBox(height: 20) : _buildAmountTextField(),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
_showCreateConfirmationDialog(context);
},
child: Text('Create'),
),
],
),
),
);
}

Widget _buildNewCropForm() {
return Column(
children: [
TextField(
controller: cropController,
decoration: InputDecoration(
labelText: 'Name of Crop',
),
),
SizedBox(height: 20),
TextField(
controller: amountController,
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly // Allow only integer input
],
decoration: InputDecoration(
labelText: 'Amount of Organic Input',
),
),
],
);
}

Widget _buildExistingCropsDropdown() {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('applications')
.where('email', isEqualTo: widget.auth.currentUser?.email)
.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}

List<String> existingCrops = snapshot.data!.docs


.map((doc) => doc['cropName'] as String)
.toSet()
.toList();

// Setting isNewCrop based on whether there are existing crops or not


isNewCrop = existingCrops.isEmpty;

return DropdownButton<String>(
value: cropController.text.isNotEmpty ? cropController.text : null,
onChanged: (String? newValue) {
setState(() {
cropController.text = newValue ?? '';
});
},
items: existingCrops.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
hint: Text('Select Existing Crop'),
);
},
);
}

Widget _buildAmountTextField() {
return TextField(
controller: amountController,
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly // Allow only integer input
],
decoration: InputDecoration(
labelText: 'Amount of Organic Input',
),
);
}

Future<void> _showCreateConfirmationDialog(BuildContext context) async {


String? cropName = cropController.text.trim();
String? amount = amountController.text.trim();
int inputAmount = int.tryParse(amount ?? '0') ?? 0;

if (isNewCrop && (cropName == null || cropName.isEmpty)) {


_showErrorDialog(context, 'Please enter crop name');
} else if (amount == null || amount.isEmpty) {
_showErrorDialog(context, 'Please enter amount');
} else {
if (inputAmount <= globalRemainingAmount) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Are you sure you want to create?'),
actions: <Widget>[
TextButton(
child: Text('No'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('Yes'),
onPressed: () {
_addToFirestore(context); // Pass context to _addToFirestore
},
),
],
);
},
);
} else {
_showErrorDialog(context, 'Amount exceeds remaining amount');
}
}
}

void _addToFirestore(BuildContext context) {


String userEmail = widget.auth.currentUser?.email ?? '';
String cropName = cropController.text.trim();
int amount = int.tryParse(amountController.text) ?? 0;

if (isNewCrop) {
_saveNewCrop(userEmail, cropName, amount, context); // Pass context
} else {
_saveExistingCrop(userEmail, cropName, amount, context); // Pass context
}
}
void _saveNewCrop(
String userEmail, String cropName, int amount, BuildContext context) {
DateTime now = DateTime.now();
String formattedDate =
"${now.year}-${now.month}-${now.day} ${now.hour}:${now.minute}:$
{now.second}";

FirebaseFirestore.instance.collection('applications').add({
'cropName': cropName,
'amount': amount,
'email': userEmail,
'organicInputId': widget.organicInputId,
'organicInputName': organicInputName,
'dateCreated': formattedDate,
'cropId': '',
}).then((DocumentReference documentReference) {
String cropId = documentReference.id;
documentReference.update({'cropId': cropId});
_redirectToCropSummary(context, cropId); // Redirect to CropSummaryPage
});
}

void _saveExistingCrop(
String userEmail, String cropName, int amount, BuildContext context) {
FirebaseFirestore.instance
.collection('applications')
.where('email', isEqualTo: userEmail)
.where('cropName', isEqualTo: cropName)
.get()
.then((QuerySnapshot snapshot) {
if (snapshot.docs.isNotEmpty) {
var existingCropDoc = snapshot.docs.first;
String cropId = existingCropDoc['cropId'] ?? '';

_saveNewCropWithCropId(
userEmail, cropName, amount, cropId, context); // Pass context
}
});
}

void _saveNewCropWithCropId(String userEmail, String cropName, int amount,


String cropId, BuildContext context) {
DateTime now = DateTime.now();
String formattedDate =
"${now.year}-${now.month}-${now.day} ${now.hour}:${now.minute}:$
{now.second}";

FirebaseFirestore.instance.collection('applications').add({
'cropName': cropName,
'amount': amount,
'email': userEmail,
'organicInputId': widget.organicInputId,
'organicInputName': organicInputName,
'dateCreated': formattedDate,
'cropId': cropId,
}).then((DocumentReference documentReference) {
_redirectToCropSummary(context, cropId); // Redirect to CropSummaryPage
});
}
void _redirectToCropSummary(BuildContext context, String cropId) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => CropSummaryPage(cropId: cropId)),
);
}

void _showErrorDialog(BuildContext context, String message) {


showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'),
content: Text(message),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'),
),
],
);
},
);
}
}

You might also like