import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.List; import java.util.Scanner; public class ReportGenerator { private final String ordersFilePath; private final List productList; private double totalFinalCost; private int totalQuantity; private double totalDiscountValue; private int totalInvalidLines; public ReportGenerator(String ordersFilePath, List productList) { this.ordersFilePath = ordersFilePath; this.productList = productList; } public void processFile() { File file = new File(ordersFilePath); if (!file.exists()) { System.err.println("File not found: " + ordersFilePath); return; } try (Scanner scanner = new Scanner(file)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.isBlank()) { continue; } try { String[] parts = line.split(","); if (parts.length != 3) { throw new Exception("Invalid line structure"); } int productID = Integer.parseInt(parts[0].trim()); int quantity = Integer.parseInt(parts[1].trim()); int discountPercent = Integer.parseInt(parts[2].trim()); if (productID <= 0 || quantity <= 0 || discountPercent < 0 || discountPercent > 99) { throw new Exception("Values out of logical bounds"); } Product matchedProduct = null; for (Product p : productList) { if (p.getProductID() == productID) { matchedProduct = p; break; } } if (matchedProduct == null) { throw new Exception("Product ID does not exist"); } double subTotal = quantity * matchedProduct.getPrice(); double discountValue = subTotal * discountPercent / 100.0; double finalCost = subTotal - discountValue; totalQuantity += quantity; totalFinalCost += finalCost; totalDiscountValue += discountValue; } catch (Exception e) { totalInvalidLines++; } } } catch (FileNotFoundException e) { System.err.println("Error opening file: " + e.getMessage()); } } public void saveReport() { String report = "========= SALES REPORT =========\n" + "Total Quantity Sold: " + totalQuantity + "\n" + "Total Final Cost: $" + totalFinalCost + "\n" + "Total Discount Value: $" + totalDiscountValue + "\n" + "Invalid Rows: " + totalInvalidLines + "\n" + "================================"; try { FileWriter writer = new FileWriter("report.txt"); writer.write(report); writer.close(); } catch (IOException e) { System.err.println("Error writing the report file"); } } }