// // AddMaintenanceView.swift // Gas Man // // Created by Kameron Kenny on 3/17/25. // import SwiftUI struct AddMaintenanceView: View { @Environment(\.managedObjectContext) private var viewContext @Environment(\.dismiss) var dismiss @State private var date = Date() @State private var odometer = "" @State private var eventType = "" @State private var cost = "" @State private var notes = "" @State private var locationCoordinates = "" @State private var locationName = "" var body: some View { NavigationView { Form { Section(header: Text("Maintenance Details")) { DatePicker("Date", selection: $date, displayedComponents: [.date, .hourAndMinute]) TextField("Odometer Reading", text: $odometer) .keyboardType(.decimalPad) TextField("Service Type", text: $eventType) TextField("Cost ($)", text: $cost) .keyboardType(.decimalPad) TextField("Notes", text: $notes) TextField("Location Coordinates", text: $locationCoordinates) TextField("Location Name", text: $locationName) } } .navigationTitle("Add Maintenance") .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button("Save") { saveMaintenance() } } ToolbarItem(placement: .navigationBarLeading) { Button("Cancel") { dismiss() } } } } } private func saveMaintenance() { let newEvent = MaintenanceEvent(context: viewContext) newEvent.id = UUID() newEvent.date = date newEvent.odometer = Double(odometer) ?? 0 newEvent.eventType = eventType newEvent.cost = Double(cost) ?? 0 newEvent.notes = notes newEvent.locationCoordinates = locationCoordinates newEvent.locationName = locationName do { try viewContext.save() dismiss() } catch { let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } }