package loanpayment;
import java.io.*;
import java.util.Scanner;
public class LoanPayment {
  public static void main(String[] args) {
     Scanner bt = new Scanner(System.in);
     String filePath = "accountsalreadyregistered.txt";
    System.out.println("Xxxxxxxxxxxxxxxxxxxxxxxxx- LOAN PAYMENT -
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxX");
    System.out.println("Log in OR Register");
System.out.println("Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxX");
     // Loop to handle invalid input for the "Sign In" or "Register" choice
     int choice = 0;
     while (true) {
        System.out.println("Choose an option:");
        System.out.println("1. Sign in");
        System.out.println("2. Register");
        System.out.print("Enter your choice (1 or 2): ");
         if (bt.hasNextInt()) {
             choice = bt.nextInt();
             bt.nextLine(); // consume the newline character
            if (choice == 1 || choice == 2) {
                break; // valid input, exit the loop
            } else {
                System.out.println("Invalid choice. Please enter 1 or 2.");
            }
         } else {
            System.out.println("Invalid input. Please enter a number (1 or 2).");
            bt.next(); // consume invalid input
         }
     }
     // Proceed based on user's choice
     if (choice == 1) {
System.out.println("Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxX");
      System.out.println("Sign in");
      System.out.print("USER ID: ");
      String userId = bt.nextLine();
      System.out.print("PASSWORD: ");
      String password = bt.nextLine();
       if (isAccountExist(filePath, userId, password)) {
           System.out.println("Welcome back! You have successfully logged in with USER ID: "
+ userId);
           showLoanMenu(bt, userId);
       } else {
           System.out.println("You don't have an account. Redirecting to registration...");
           register(bt, filePath);
       }
      } else if (choice == 2) {
         register(bt, filePath);
      }
  }
  public static boolean isAccountExist(String filePath, String userId, String password) {
    try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
       String line;
       while ((line = reader.readLine()) != null) {
          String[] account = line.split(",");
          if (account[0].equals(userId) && account[1].equals(password)) {
              return true;
          }
       }
    } catch (FileNotFoundException e) {
       System.out.println("No accounts found. Please register first.");
    } catch (IOException e) {
       e.printStackTrace();
    }
    return false;
  }
  public static void saveAccount(String filePath, String idType, String gender, String firstName,
String lastName, String middleName,
                       Integer age, String dob, String address, String email, String
contactNumber,
                       String userId, String password) {
     try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
        writer.write(userId + "," + password + "," + idType + "," + gender + "," + firstName + "," +
lastName + "," + middleName + ","
             + age + "," + dob + "," + address + "," + email + "," + contactNumber);
        writer.newLine();
     } catch (IOException e) {
        e.printStackTrace();
     }
   }
  public static void register(Scanner bt, String filePath) {
System.out.println("Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxX");
    System.out.println("Register");
    System.out.println("PERSONAL INFORMATION:");
     // ID Type Selection with invalid input handling
     System.out.println("ID Type:");
     System.out.println("1. Philippine Passport (DFA)");
     System.out.println("2. National ID");
     System.out.println("3. SSS ID or SSS UMID Card (SSS)");
     System.out.println("4. GSIS ID or GSIS UMID Card (GSIS)");
     System.out.println("5. Driver's License (LTO)");
     System.out.println("6. Voter's ID (COMELEC)");
     System.out.println("7. Senior Citizen ID (LGU)");
     System.out.println("8. PWD ID (LGU)");
     System.out.println("9. NBI Clearance");
     System.out.println("10. PhilHealth ID");
     System.out.println("11. Government Office/GOCC ID");
     int idChoice = -1;
     while (idChoice < 1 || idChoice > 11) {
        System.out.print("Enter your ID choice (1-11): ");
        if (bt.hasNextInt()) {
            idChoice = bt.nextInt();
            if (idChoice < 1 || idChoice > 11) {
                System.out.println("Invalid choice. Please select a valid ID type.");
            }
        } else {
            System.out.println("Invalid input. Please enter a number between 1 and 11.");
            bt.next(); // consume invalid input
        }
}
bt.nextLine(); // consume newline
String idType = getIdType(idChoice);
// Gender Input with invalid input handling
String gender = "";
while (!gender.equalsIgnoreCase("Male") && !gender.equalsIgnoreCase("Female")) {
   System.out.print("Enter your GENDER (Male/Female): ");
   gender = bt.nextLine();
   if (!gender.equalsIgnoreCase("Male") && !gender.equalsIgnoreCase("Female")) {
       System.out.println("Invalid input. Please enter 'Male' or 'Female'.");
   }
}
// Name Inputs with Validation
String firstName = "";
while (firstName.isEmpty()) {
   System.out.print("FIRSTNAME: ");
   firstName = bt.nextLine();
   if (firstName.isEmpty()) {
       System.out.println("First name is required. Please enter it.");
   }
}
String lastName = "";
while (lastName.isEmpty()) {
  System.out.print("LASTNAME: ");
  lastName = bt.nextLine();
  if (lastName.isEmpty()) {
      System.out.println("Last name is required. Please enter it.");
  }
}
System.out.print("MIDDLE NAME: (optional) ");
String middleName = bt.nextLine();
// Age Input with Validation
Integer age = null;
while (age == null || age < 18) {
   System.out.print("AGE: ");
   if (bt.hasNextInt()) {
       age = bt.nextInt();
       if (age < 18) {
           System.out.println("Sorry, you must be at least 18 years old to register.");
     }
  } else {
     System.out.println("Please enter a valid number for age.");
     bt.next(); // consume invalid input
  }
}
bt.nextLine(); // consume newline
// Date of Birth Input
String dob = "";
while (dob.isEmpty()) {
   System.out.print("DATE OF BIRTH (e.g., 01/01/1990): ");
   dob = bt.nextLine();
   if (dob.isEmpty()) {
       System.out.println("Date of birth is required.");
   }
}
// Address Input
String address = "";
while (address.isEmpty()) {
   System.out.print("ADDRESS: ");
   address = bt.nextLine();
   if (address.isEmpty()) {
       System.out.println("Address is required.");
   }
}
// Email Input
String email = "";
while (email.isEmpty()) {
   System.out.print("EMAIL: ");
   email = bt.nextLine();
   if (email.isEmpty()) {
       System.out.println("Email is required.");
   }
}
// Contact Number Input
String contactNumber = "";
while (contactNumber.isEmpty()) {
   System.out.print("CONTACT NUMBER (e.g., 09********1): ");
   contactNumber = bt.nextLine();
   if (contactNumber.isEmpty()) {
            System.out.println("Contact number is required.");
        }
    }
    // User ID and Password Input
    String userId = "";
    while (userId.isEmpty()) {
       System.out.print("USER ID: ");
       userId = bt.nextLine();
       if (userId.isEmpty()) {
           System.out.println("User ID is required.");
       }
    }
    String password = "";
    while (password.isEmpty()) {
      System.out.print("PASSWORD: ");
      password = bt.nextLine();
      if (password.isEmpty()) {
          System.out.println("Password is required.");
      }
    }
    // Save the account
    saveAccount(filePath, idType, gender, firstName, lastName, middleName, age, dob,
address, email, contactNumber, userId, password);
System.out.println("Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxX");
    System.out.println("Thank you for registering! Here are your details:");
    System.out.println("ID TYPE: " + idType);
    System.out.println("GENDER: " + gender);
    System.out.println("FIRSTNAME: " + firstName);
    System.out.println("LASTNAME: " + lastName);
    System.out.println("MIDDLE NAME: " + middleName);
    System.out.println("AGE: " + age);
    System.out.println("DATE OF BIRTH: " + dob);
    System.out.println("ADDRESS: " + address);
    System.out.println("EMAIL: " + email);
    System.out.println("CONTACT NUMBER: " + contactNumber);
    System.out.println("USER ID: " + userId);
    System.out.println("You have successfully registered.");
      // Redirect to the Home Screen after Registration
      System.out.println("Redirecting to the Home Screen...");
      showLoanMenu(bt, userId); // Direct to home screen after registration
  }
  public static String getIdType(int idChoice) {
    switch (idChoice) {
       case 1: return "Philippine Passport (DFA)";
       case 2: return "National ID";
       case 3: return "SSS ID or SSS UMID Card (SSS)";
       case 4: return "GSIS ID or GSIS UMID Card (GSIS)";
       case 5: return "Driver's License (LTO)";
       case 6: return "Voter's ID (COMELEC)";
       case 7: return "Senior Citizen ID (LGU)";
       case 8: return "PWD ID (LGU)";
       case 9: return "NBI Clearance";
       case 10: return "PhilHealth ID";
       case 11: return "Government Office/GOCC ID";
    }
    return null;
  }
  public static void showLoanMenu(Scanner bt, String userId) {
    boolean continueMenu = true;
      while (continueMenu) {
System.out.println("Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxX");
      System.out.println("Home Screen - Loan Management Menu:");
      System.out.println("1. Apply for a Loan");
      System.out.println("2. Check Loan Status");
      System.out.println("3. Make Loan Repayment");
      System.out.println("4. View Loan History");
      System.out.println("5. View Personal Information");
      System.out.println("6. Exit");
      System.out.print("Enter your choice (1-6): ");
      int loanChoice = bt.nextInt();
      bt.nextLine();
        switch (loanChoice) {
          case 1:
             applyForLoan(bt, userId);
             break;
              case 2:
                checkLoanStatus(userId);
                break;
              case 3:
                makeLoanRepayment(bt, userId);
                break;
              case 4:
                viewLoanHistory(userId);
                break;
              case 5:
                viewPersonalInformation(userId); // View personal information
                break;
              case 6:
                continueMenu = false; // Exit the loop and return to the main menu
                break;
              default:
                System.out.println("Invalid choice. Please try again.");
          }
      }
  }
   public static void viewPersonalInformation(String userId) {
     System.out.println("Fetching personal information for USER ID: " + userId);
     try (BufferedReader reader = new BufferedReader(new
FileReader("accountsalreadyregistered.txt"))) {
        String line;
        while ((line = reader.readLine()) != null) {
           String[] account = line.split(",");
           if (account[0].equals(userId)) {
               System.out.println("ID TYPE: " + account[2]);
               System.out.println("GENDER: " + account[3]);
               System.out.println("FIRSTNAME: " + account[4]);
               System.out.println("LASTNAME: " + account[5]);
               System.out.println("MIDDLE NAME: " + account[6]);
               System.out.println("AGE: " + account[7]);
               System.out.println("DATE OF BIRTH: " + account[8]);
               System.out.println("ADDRESS: " + account[9]);
               System.out.println("EMAIL: " + account[10]);
               System.out.println("CONTACT NUMBER: " + account[11]);
               System.out.println("USER ID: " + account[0]);
           }
        }
     } catch (IOException e) {
        e.printStackTrace();
    }
}
// Placeholder methods for loan management features
public static void checkLoanStatus(String userId) {
   System.out.println("Checking loan status for USER ID: " + userId);
   // Implement the logic for checking loan status here
}
public static void makeLoanRepayment(Scanner bt, String userId) {
  System.out.println("Making loan repayment for USER ID: " + userId);
  // Implement loan repayment logic here
}
public static void viewLoanHistory(String userId) {
  System.out.println("Viewing loan history for USER ID: " + userId);
  // Implement loan history view logic here
}
public static void applyForLoan(Scanner bt, String userId) {
System.out.println("Before you apply for the loan, please answer the following questions:");
// Question 1: Do you have a steady source of income? (Yes/No)
String income = "";
while (!income.equalsIgnoreCase("Yes") && !income.equalsIgnoreCase("No")) {
   System.out.println("Question 1: Do you have a steady source of income? (Yes/No): ");
   income = bt.nextLine();
   if (!income.equalsIgnoreCase("Yes") && !income.equalsIgnoreCase("No")) {
       System.out.println("Invalid input. Please answer 'Yes' or 'No'.");
   }
}
// Question 2: Have you taken a loan in the last 6 months? (Yes/No)
String loanHistory = "";
while (!loanHistory.equalsIgnoreCase("Yes") && !loanHistory.equalsIgnoreCase("No")) {
   System.out.println("Question 2: Have you taken a loan in the last 6 months? (Yes/No): ");
   loanHistory = bt.nextLine();
   if (!loanHistory.equalsIgnoreCase("Yes") && !loanHistory.equalsIgnoreCase("No")) {
       System.out.println("Invalid input. Please answer 'Yes' or 'No'.");
   }
}
// Question 3: Are you currently employed? (Yes/No)
String employmentStatus = "";
  while (!employmentStatus.equalsIgnoreCase("Yes") && !
employmentStatus.equalsIgnoreCase("No")) {
    System.out.println("Question 3: Are you currently employed? (Yes/No): ");
    employmentStatus = bt.nextLine();
    if (!employmentStatus.equalsIgnoreCase("Yes") && !
employmentStatus.equalsIgnoreCase("No")) {
        System.out.println("Invalid input. Please answer 'Yes' or 'No'.");
    }
  }
  // Question 4: Do you have any existing loans? (Yes/No)
  String existingLoans = "";
  while (!existingLoans.equalsIgnoreCase("Yes") && !existingLoans.equalsIgnoreCase("No")) {
     System.out.println("Question 4: Do you have any existing loans? (Yes/No): ");
     existingLoans = bt.nextLine();
     if (!existingLoans.equalsIgnoreCase("Yes") && !existingLoans.equalsIgnoreCase("No")) {
         System.out.println("Invalid input. Please answer 'Yes' or 'No'.");
     }
  }
  // Question 5: What is your monthly salary?
  double monthlySalary = -1;
  while (monthlySalary <= 0) {
     System.out.print("Question 5: What is your monthly salary? ");
     if (bt.hasNextDouble()) {
         monthlySalary = bt.nextDouble();
         bt.nextLine(); // consume the newline
         if (monthlySalary <= 0) {
             System.out.println("Please enter a valid positive number for salary.");
         }
     } else {
         System.out.println("Invalid input. Please enter a valid number for salary.");
         bt.next(); // consume invalid input
     }
  }
  // Loan calculation based on salary
  double loanAmount = 0;
  double interestRate = 0;
  int repaymentPeriod = 0;
  if (monthlySalary <= 15000) {
      loanAmount = 25000; // max loan
      interestRate = 0.08; // 8% interest
       repaymentPeriod = (int)(Math.random() * 4) + 3; // 3 to 6 months
    } else if (monthlySalary <= 30000) {
       loanAmount = 50000; // max loan
       interestRate = 0.10; // 10% interest
       repaymentPeriod = (int)(Math.random() * 4) + 3; // 3 to 6 months or 12 months
    } else if (monthlySalary >= 50000) {
       loanAmount = 100000; // max loan
       interestRate = 0.12; // 12% interest
       repaymentPeriod = (int)(Math.random() * 3) + 6; // 6 to 12 months or 18 months
    }
   // Simulate Loan Application Approval Based on Answers
   if (income.equalsIgnoreCase("Yes") && loanHistory.equalsIgnoreCase("No") &&
employmentStatus.equalsIgnoreCase("Yes")
          && existingLoans.equalsIgnoreCase("No")) {
       System.out.println("Congratulations, your loan application is approved!");
       System.out.println("You are eligible for a loan of " + loanAmount + " with an interest rate of
" + (interestRate * 100) + "%.");
       System.out.println("Repayment period: " + repaymentPeriod + " months.");
       double totalAmount = loanAmount + (loanAmount * interestRate);
       System.out.println("Total amount to be repaid: " + totalAmount);
   } else {
       System.out.println("Sorry, your loan application has been rejected due to one or more
criteria not being met.");
   }
}