import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.List; 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() { try (BufferedReader reader = new BufferedReader(new FileReader(ordersFilePath))) { String line; while ((line = reader.readLine()) != null) { String[] parts = line.split(","); if (parts.length != 3) { totalInvalidLines++; continue; } try { int id = Integer.parseInt(parts[0]); int quantity = Integer.parseInt(parts[1]); int discountPercent = Integer.parseInt(parts[2]); if (id <= 0 || quantity <= 0 || discountPercent < 0 || discountPercent > 99) { totalInvalidLines++; continue; } Product product = findProductById(id); if (product == null) { totalInvalidLines++; continue; } double subtotal = quantity * product.getPrice(); double discountValue = subtotal * discountPercent / 100.0; double finalCost = subtotal - discountValue; totalQuantity += quantity; totalFinalCost += finalCost; totalDiscountValue += discountValue; } catch (NumberFormatException e) { totalInvalidLines++; } } } catch (IOException e) { System.err.println("Error reading order file: " + e.getMessage()); } } private Product findProductById(int id) { for (Product p : productList) { if (p.getProductID() == id) { return p; } } return null; } public void saveReport() { String report = String.format( "========= SALES REPORT =========\n" + "Total Quantity Sold: %d\n" + "Total Final Cost: $%.2f\n" + "Total Discount Value: $%.2f\n" + "Invalid Rows: %d\n" + "================================\n", totalQuantity, totalFinalCost, totalDiscountValue, totalInvalidLines ); try (FileWriter writer = new FileWriter("report.txt")) { writer.write(report); } catch (IOException e) { System.err.println("Error saving report: " + e.getMessage()); } } }