package com.avitam.bankloanapplication.pdfGenerator;

import com.avitam.bankloanapplication.model.dto.LoanEmiDetailDto;
import com.avitam.bankloanapplication.model.entity.Customer;
import com.avitam.bankloanapplication.model.entity.Loan;
import com.avitam.bankloanapplication.model.entity.LoanApplication;
import com.avitam.bankloanapplication.model.entity.LoanTemplate;
import com.avitam.bankloanapplication.model.entity.LoanType;
import com.avitam.bankloanapplication.repository.CustomerRepository;
import com.avitam.bankloanapplication.repository.LoanApplicationRepository;
import com.avitam.bankloanapplication.repository.LoanRepository;
import com.avitam.bankloanapplication.repository.LoanTemplateRepository;
import com.avitam.bankloanapplication.repository.LoanTypeRepository;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class PdfGenerator {

    private static final String reportFileName = "Shree Meenakshi Finance";
    private static final String signature = "Signature";
    private static final String website = "www.shreemeenakshifinance.com";
    private static final String platformProcessingFees = "5250";
    private static final String platformOneTimeOnboardingCharges = "350";
    private static final String platformLatePaymentCharges = "Penalty charges applicable on repayment post due date " +
            "for each instalment:\n" + "First Overdue Day penalty charges 500 INR\n" + "Penalty charges for 2-90 days 0.1 % of principal*\n" +
            "*round to nearest rupee";
    private static final Font HELVETICA = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD);
    private static final Font HELVETICA_SMALL = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);
    private static final Font HELVETICA_SMALL_BOLD = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
    private static final Font HELVETICA_SMALLER_BOLD = new Font(Font.FontFamily.HELVETICA, 8, Font.BOLD);
    private static final Font HELVETICA_SMALL_FOOTER = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
    private static final Font HELVETICA_SMALL_BOLD_UNDERLINE = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD | Font.UNDERLINE);
    Logger LOG = LoggerFactory.getLogger(PdfGenerator.class);
    @Autowired
    private LoanTemplateRepository loanTemplateRepository;
    @Autowired
    private LoanTypeRepository loanTypeRepository;
    @Autowired
    private LoanApplicationRepository loanApplicationRepository;
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private LoanRepository loanRepository;

    private static void leaveEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }

    public ByteArrayOutputStream sanctionLetterPdf(String loanApplicationId) {
        Document document = new Document();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {
            PdfWriter.getInstance(document, byteArrayOutputStream);
            document.open();
            addTitleAndLogo(document);
            addLoanPdfContents(document, loanApplicationId);
            addTermsAndConditions(document);
            addFooter(document);
            document.close();
        } catch (DocumentException e) {
            LOG.error(e.getMessage(), e);
        }

        return byteArrayOutputStream;
    }

    public ByteArrayOutputStream annexureBPdf(String loanId) {
        Document document = new Document();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {
            Loan loan = loanRepository.findByRecordId(loanId);
            PdfWriter.getInstance(document, byteArrayOutputStream);
            document.open();
            addAnnexureB_PdfContents(document, loan);
            createLoanEmiDetailsTable(document, loan);
            addAdditionalTermsAndConditions(document, loan);
            document.close();
        } catch (DocumentException e) {
            LOG.error(e.getMessage(), e);
        }

        return byteArrayOutputStream;
    }

    public ByteArrayOutputStream noObjectionCertificatePdf(String loanId) {
        Document document = new Document();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {
            PdfWriter.getInstance(document, byteArrayOutputStream);
            document.open();
            Loan loan = loanRepository.findByRecordId(loanId);

            addNOC_PdfContents(document, loan);
            createLoanEmiDetailsTable(document, loan);
            addNOC_PdfContents2(document, loan);
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return byteArrayOutputStream;
    }

    private void addNOC_PdfContents(Document document, Loan loan) throws DocumentException {

        Customer customer = customerRepository.findByRecordId(loan.getCustomerId());
        LoanType loanType = loanTypeRepository.findByRecordId(loan.getLoanType());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
        String date = simpleDateFormat.format(new Date());
        String date2 = "Date: " + date;

        Paragraph paragraph1 = new Paragraph("NO OBJECTION CERTIFICATE", HELVETICA_SMALL_BOLD);
        paragraph1.setAlignment(Element.ALIGN_CENTER);
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph(date2, HELVETICA_SMALL);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        Paragraph paragraph3 = new Paragraph();
        leaveEmptyLine(paragraph3, 1);
        document.add(paragraph3);

        String customerNameAddress = "To, " + "\n" +
                customer.getFullName() + "\n" +
                customer.getAddress();

        Paragraph paragraph4 = new Paragraph(customerNameAddress, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph3, 1);
        document.add(paragraph4);

        Paragraph paragraph5 = new Paragraph();
        leaveEmptyLine(paragraph5, 1);
        document.add(paragraph5);

        String subject = "Subject: Loan Closure & No Objection Certificate for Loan A/c No. " + loan.getRecordId();

        Paragraph paragraph6 = new Paragraph(subject, HELVETICA_SMALL);
        paragraph6.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph6, 1);
        document.add(paragraph6);

        Paragraph paragraph7 = new Paragraph();
        leaveEmptyLine(paragraph7, 1);
        document.add(paragraph7);

        String content = "Dear Sir/Madam, " + "\n" + "\n"
                + "This is to certify that you, " + customer.getFullName() + " had availed a "
                + loanType.getName() + " from " + reportFileName + " under Loan Account Number " + loan.getRecordId() + "." + "\n" + "\n"
                + "The loan was sanctioned on " + loan.getSanctionDate() + " for an amount of Rs " + loan.getDesiredLoan() +
                " to be repaid in " + loan.getTenure() + " monthly installments of Rs " + loan.getLoanEmiDetailDtoList().get(0).getInstalment() + " each. " +
                "We confirm that all installments have been paid as per schedule and the " +
                "loan account now stands **fully closed with NIL outstanding balance**";

        Paragraph paragraph8 = new Paragraph(content, HELVETICA_SMALL);
        paragraph8.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph8, 1);
        document.add(paragraph8);

    }

    private void addNOC_PdfContents2(Document document, Loan loan) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        String content = "We hereby confirm that your loan account has been closed on " + loan.getClosureDate() + "," +
                " and we have no further claim or objection in respect of the above-mentioned loan. ";

        Paragraph paragraph2 = new Paragraph(content, HELVETICA_SMALL);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        Paragraph paragraph3 = new Paragraph();
        leaveEmptyLine(paragraph3, 1);
        document.add(paragraph3);

        String sincerely = "Sincerely, " + "\n"
                + "For " + reportFileName;

        Paragraph paragraph4 = new Paragraph(sincerely, HELVETICA_SMALL);
        paragraph4.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph4, 1);
        document.add(paragraph4);
    }

    public ByteArrayOutputStream loanAggrementPdf(String loanId) {
        Document document = new Document();
        Loan loan = loanRepository.findByRecordId(loanId);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {
            Customer customer = customerRepository.findByRecordId(loan.getCustomerId());
            PdfWriter pdfWriter = PdfWriter.getInstance(document, byteArrayOutputStream);
            pdfWriter.setPageEvent(new PageNumberEvent());
            document.open();
            addLoanApplicationForm(document, loan, customer);
            addSummaryOfLoanTerms(document, loan, customer);
            addParticularsAndDetails(document, loan);
            addDocumentsFromApplicantAndCoApplicant(document, customer);
            addSelfDeclarationAndUndertaking(document);
            addIncomeDeclaration(document, customer);
            addStandardTermsAndConditions(document);
            addDefinitions(document);
            addInterpretations(document);
            addSanctionAndDisbursement(document);
            addInterestAndOtherCharges(document);
            addPayments(document);
            addRepresentationsAndWarranties(document);
            addCovenants(document);
            addEventOfDefault(document);
            addConsequencesOfEventOfDefault(document);
            addMiscellaneous(document);
            addGrievanceRedressalMechanismOfThePlatform(document);
            addGrievanceRedressalMechanismOfTheLender(document);
            addAnnexureA(document, loan, customer);
            addAnnexureB(document);
            createLoanEmiDetailsTable(document, loan);
            addAnnexureBNoteAndAcknowledgement(document);
            addPanAadharProfileImages(document, customer);
            document.close();
        } catch (DocumentException | IOException e) {
            LOG.error(e.getMessage(), e);
        }

        return byteArrayOutputStream;
    }

    private void addLoanApplicationForm(Document document, Loan loan, Customer customer) throws DocumentException {

        Paragraph paragraph1 = new Paragraph("LOAN APPLICATION FORM", HELVETICA_SMALL_BOLD_UNDERLINE);
        paragraph1.setAlignment(Element.ALIGN_CENTER);
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        String[][] tableData = {
                {"ACCOUNT TYPE", loan.getRecordId()},
                {"NAME", customer.getName()},
                {"FATHER/SPOUSE NAME", customer.getFatherName()},
                {"MOTHER'S NAME", customer.getMotherName()},
                {"DATE OF BIRTH", customer.getDateOfBirth()},
                {"GENDER", customer.getGender()},
                {"MARITAL STATUS", customer.getMaritalStatus()},
                {"OCCUPATION", customer.getEmploymentType()},
                {"NATIONALITY", customer.getNationality()},
                {"RESIDENTIAL STATUS", customer.getResidentialStatus()},
                {"PAN", customer.getPanNumber()},
                {"PROOF OF ADDRESS/IDENTITY", customer.getAddressProof()},
                {"ADDRESS TYPE", customer.getAddressType()},
                {"ADDRESS", customer.getAddress()},
                {"CURRENT ADDRESS", customer.getCurrentAddress()},
                {"PHONE NUMBER", customer.getPhone()},
                {"EMAIL", customer.getEmail()},
                {" RELATED PERSON", "Name: " + customer.getRelatedPersonName1() + "\n"
                        + "Relation: " + customer.getRelatedPersonRelation1() + "\n"
                        + "Contact No: " + customer.getRelatedPersonContactNumber1() + "\n"
                        + "Name: " + customer.getRelatedPersonName2() + "\n"
                        + "Relation: " + customer.getRelatedPersonRelation2() + "\n"
                        + "Contact No: " + customer.getRelatedPersonContactNumber2() + "\n"}

        };

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new float[]{50f, 50f});

        Font boldFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
        Font normalFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);

        for (String[] row : tableData) {
            for (int i = 0; i < row.length; i++) {
                Font currentFont = (i == 0) ? boldFont : normalFont;
                PdfPCell cell = new PdfPCell(new Phrase(row[i], currentFont));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setMinimumHeight(35f);
                table.addCell(cell);
            }
        }

        document.add(table);
    }

    private void addSummaryOfLoanTerms(Document document, Loan loan, Customer customer) throws DocumentException {

        Paragraph paragraph = new Paragraph();
        leaveEmptyLine(paragraph, 3);
        document.add(paragraph);

        PdfPTable table = new PdfPTable(3);
        table.setWidthPercentage(100);
        table.setWidths(new float[]{10f, 25f, 65f});

        PdfPCell cell1 = new PdfPCell(new Phrase("SUMMARY OF THE LOAN TERMS", HELVETICA_SMALL_BOLD));
        cell1.setColspan(3);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell1.setMinimumHeight(30f);
        table.addCell(cell1);

        PdfPCell cell2 = new PdfPCell(new Phrase("S NO.", HELVETICA_SMALL_BOLD));
        cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell2.setMinimumHeight(30f);
        table.addCell(cell2);

        PdfPCell cell3 = new PdfPCell(new Phrase("PARTICULARS", HELVETICA_SMALL_BOLD));
        cell3.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell3.setMinimumHeight(30f);
        table.addCell(cell3);

        PdfPCell cell4 = new PdfPCell(new Phrase("DETAILS", HELVETICA_SMALL_BOLD));
        cell4.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell4.setMinimumHeight(30f);
        table.addCell(cell4);

        PdfPCell cell5 = new PdfPCell(new Phrase("1", HELVETICA_SMALL_BOLD));
        cell5.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell5.setMinimumHeight(30f);
        table.addCell(cell5);

        PdfPCell cell6 = new PdfPCell(new Phrase("LOAN ID/ SERIAL ID", HELVETICA_SMALL_BOLD));
        cell6.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell6.setMinimumHeight(30f);
        table.addCell(cell6);

        PdfPCell cell7 = new PdfPCell(new Phrase(loan.getRecordId(), HELVETICA_SMALL));
        cell7.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell7.setMinimumHeight(30f);
        table.addCell(cell7);

        PdfPCell cell8 = new PdfPCell(new Phrase("2", HELVETICA_SMALL_BOLD));
        cell8.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell8.setMinimumHeight(30f);
        table.addCell(cell8);

        PdfPCell cell9 = new PdfPCell(new Phrase("CITY", HELVETICA_SMALL_BOLD));
        cell9.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell9.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell9.setMinimumHeight(30f);
        table.addCell(cell9);

        PdfPCell cell10 = new PdfPCell(new Phrase(customer.getAddress(), HELVETICA_SMALL));
        cell10.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell10.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell10.setMinimumHeight(30f);
        table.addCell(cell10);

        document.add(table);
    }

    private void addParticularsAndDetails(Document document, Loan loan) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        String terms = "I understand the terms of the loan to be provide to Me as may be approved by the Lender as per its" +
                " internal policies and law shall be as specified below (\"Loan\"):";

        Paragraph paragraph2 = new Paragraph(terms, HELVETICA_SMALL);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String[][] tableData = {
                {" PARTICULARS\n" +
                        "(Below charges are in INR and exclusive of GST).", "DETAILS"},
                {"LENDER", reportFileName},
                {"PLATFORM", website},
                {"LOAN AMOUNT", String.valueOf(loan.getDesiredLoan())},
                {"RATE OF INTEREST", loan.getInterestRate() + "% Per Annum"},
                {"PURPOSE OF LOAN", loan.getRecordId()},
                {"PLATFORM PROCESSING FEES", platformProcessingFees},
                {"PLATFORM ONE TIME ONBOARDING CHARGES", platformOneTimeOnboardingCharges},
                {"PLATFORM LATE PAYMENT CHARGES", platformLatePaymentCharges},
                {"PREPAYMENT CHARGES\n" + " (i) In case of prepayment of any instalment/ part prepayment: \n" +
                        " (ii) In case of prepayment in full:", "NIL"},
                {"Disbursal details for Loan", "BANK: HXXXX BANK\n" + "Bank A/C NO. 0166XXXXXXX\n" + "IFSC: HDXXXXXXX00"},

        };

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new float[]{50f, 50f});

        Font boldFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
        Font normalFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);

        for (int rowIndex = 0; rowIndex < tableData.length; rowIndex++) {
            String[] row = tableData[rowIndex];

            for (int colIndex = 0; colIndex < row.length; colIndex++) {
                Font currentFont;

                if (rowIndex == 0) {
                    currentFont = boldFont;
                } else {
                    currentFont = (colIndex == 0) ? boldFont : normalFont;
                }
                PdfPCell cell = new PdfPCell(new Phrase(row[colIndex], currentFont));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setMinimumHeight(40f);
                table.addCell(cell);
            }
        }

        document.add(table);
    }

    private void addDocumentsFromApplicantAndCoApplicant(Document document, Customer customer) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 5);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("I agree to submit the following documents for availing of Loan:", HELVETICA_SMALL);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String[][] tableData = {
                {"S. No.", "Documents from the Applicant and the Co-Applicant (if any)", "Status"},
                {"1", "PAN Card or Form 60", customer.getDocumentSubmitted()},
                {"2", "Passport/Voter ID/Redacted Aadhaar/Driver License", customer.getAddressProof()},
                {"3", " Any other document requested by Lender", ""},
        };

        PdfPTable table = new PdfPTable(3);
        table.setWidthPercentage(100);
        table.setWidths(new float[]{10f, 75f, 15f});

        Font boldFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
        Font normalFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);

        for (int rowIndex = 0; rowIndex < tableData.length; rowIndex++) {
            String[] row = tableData[rowIndex];

            for (int colIndex = 0; colIndex < row.length; colIndex++) {
                Font currentFont = (rowIndex == 0) ? boldFont : normalFont;

                PdfPCell cell = new PdfPCell(new Phrase(row[colIndex], currentFont));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setMinimumHeight(30f);
                table.addCell(cell);
            }
        }

        document.add(table);

        Paragraph paragraph3 = new Paragraph();
        leaveEmptyLine(paragraph3, 1);
        document.add(paragraph3);

        String acknowledgement = "I acknowledge, understand and agree that Lender has adopted risk-based pricing, which is arrived by" +
                " taking into account, broad parameters like the customers financial and credit profile. I also understand all" +
                " the terms listed above along with certain fees/ charges (as may be applicable) apply for the said Loan" +
                " from the Lender. I further understand and acknowledge that as may be applicable the Platform" +
                " Processing Fees,  Platform One Time Onboarding Fees, Platform Credit Reassessment Fees, Platform" +
                " Late Payment Charges, Platform Document Collection Charges, Platform Agreement Fees, Prepayment" +
                " Charges, Down payment  and Platform Credit Report Charges along with applicable taxes shall be paid to" +
                " and collected by the platform- XXXXXX Tech Solution Private Limited (GST NO- 29XXXXXXXX)" +
                " (\"Platform\" or \"Shree Meenakshi Finance\"), which is a distinct and separate entity from the Lender. The Lender is not" +
                " liable to collect any such fee & charges and to pay any applicable taxes on the same. I have accepted" +
                " that the acceptance of Loan under this Application Form places no obligation on the Lender to approve" +
                " the Loan.";

        Paragraph paragraph4 = new Paragraph(acknowledgement, HELVETICA_SMALL);
        paragraph4.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph4);
    }

    private void addSelfDeclarationAndUndertaking(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("SELF-DECLARATION AND UNDERTAKING:", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String selfDeclaration = "1. I hereby apply for the Facility from the Lender as specified above.\n" +
                "2. I represent that the information and details provided in this Application Form and the documents" +
                " submitted by me are true, correct and that I have not concealed any information.\n" +
                "3. I have read and understood the fees and charges as may be applicable to the Loan that I may avail" +
                " from time to time.\n" +
                "4. I confirm that no insolvency proceedings or suits for recovery of outstanding dues have been initiated" +
                " and / or are pending against me.\n" +
                "5. I hereby authorize Lender to exchange or share information and details relating to this Application" +
                " Form its group companies or any third party, as may be required or deemed fit, for the purpose of" +
                " processing this loan application and/or related offerings or other products / services that I may apply from" +
                " time to time.\n" +
                "6. I hereby consent to and authorize Lender to increase or decrease the credit limit assigned to me basis" +
                " Lender's internal credit policy.\n" +
                "7. By submitting this Application Form, I hereby expressly authorize Lender to send me communications" +
                " regarding various financial products offered by or from Lender, its group companies and / or third parties" +
                " through telephone calls / SMSs / emails / post etc. including but not limited to promotional" +
                " communications and confirm that I shall not challenge receipt of such communications as unsolicited" +
                " communication, defined under TRAI Regulations on Unsolicited Commercial Communications under the" +
                " Do Not Call Registry.\n" +
                "8. I understand and acknowledge that the Lender has the absolute discretion, without assigning any" +
                " reasons to reject my application and that the Lender is not liable to provide me a reason for the same.\n" +
                "9. That Lender shall have the right to make disclosure of any information including my Aadhar number" +
                " relating to me including personal information, details in relation to Loan, defaults, security, etc. to the" +
                " Credit Information Bureau of India (CIBIL) and/or any other governmental/regulatory/statutory or private" +
                " agency / entity, credit bureau, RBI, CKYCR, including publishing the name as part of wilful defaulters' list" +
                " from time to time, as also use for KYC information verification, credit risk analysis, or for any other related" +
                " purposes.\n" +
                "10. I agree and accept that Lender may in its sole discretion, by itself or through authorised persons," +
                " advocate, agencies, bureau, etc. verify any information given, check credit references, employment" +
                " details and obtain credit reports to determine my creditworthiness from time to time.\n" +
                "11. I authorize the Lender to run credit checks on my behalf and obtain my credit report for the purpose" +
                " assessing my eligibility for the loan application submitted by me and I provide my express consent to the" +
                " Lender to share such credit report with other lenders in connection with my loan application with such" +
                " lenders through Kreditbee mobile application. That I have not taken any loan from any other bank/ finance" +
                " company unless specifically declared by me.\n" +
                "12. That the funds shall be used for the Purpose specified above and will not be used for any illegal," +
                " speculative or antisocial purpose.\n" +
                "13. I consent that the related person(s) may be contacted in verification of my identity, reference and" +
                " repayment capability in case of delay or default in repayment of any EMI(s)/ FMI(s) but for any collections" +
                " requests directly from them.\n" +
                "14. I have clearly understood and accepted all the payments and charges listed above.\n" +
                "15. I hereby confirm that I contacted the Lender for my own personal requirement of personal loan and no" +
                " representative of Lender has emphasized or induced me directly / indirectly to make this application for" +
                " the Loan.\n" +
                "16. I consent to and authorize Lender to increase or decrease the credit limit assigned to me basis the" +
                " Lender's internal credit policy.\n" +
                "17. I understand and accept that no moratorium or deferment of EMI/ FMI will be provided by the Lender" +
                " (as per the Lender's policy on EMI Moratorium) on the Facility under this Application Form and there shall" +
                " be no demur or protest by me in this regard.\n";

        Paragraph paragraph3 = new Paragraph(selfDeclaration, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

        String hereby = "I hereby confirm having read and understood the Standard Terms and Conditions applicable to" +
                " this Loan and I am signing this Application Form after understanding and acceptance of each" +
                " term.\n";

        Paragraph paragraph4 = new Paragraph(hereby, HELVETICA_SMALL_BOLD);
        paragraph4.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph4);
    }

    private void addIncomeDeclaration(Document document, Customer customer) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 7);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("Income declaration", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_CENTER);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        Paragraph paragraph3 = new Paragraph("I represent that the information and details provided below by me are true, correct and that I have not" +
                " concealed any information therefrom;", HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph3, 1);
        document.add(paragraph3);

        Paragraph paragraph4 = new Paragraph("i. My monthly income is " + customer.getMonthlyIncome() + " INR\n" +
                "ii. I agree that my monthly Household Income (including income from all people residing in my" +
                " house) is greater than Rs. " + customer.getMonthlyIncome(), HELVETICA_SMALL);
        paragraph4.setAlignment(Element.ALIGN_LEFT);
        paragraph4.setIndentationLeft(20f);
        leaveEmptyLine(paragraph4, 34);
        document.add(paragraph4);

    }

    private void addStandardTermsAndConditions(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("STANDARD TERMS AND CONDITIONS", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_CENTER);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String termsAndConditions = "The Borrower may apply for loans by submitting the Application Form, and Lender as specified in the" +
                " Application Form (\"Lender\") may agree to grant the loan that are or will be governed by these terms and" +
                " conditions (\"Standard Terms\") read together with the Application Form, and Most Important Terms and" +
                " Conditions (\"MITC\") as exchanged between the parties (together referred to as \"Transaction Document\").";

        Paragraph paragraph3 = new Paragraph(termsAndConditions, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

    }

    private void addDefinitions(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("1. Definitions:", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String definitions = "In these Standard Terms unless there is anything repugnant to the subject or context thereof, the" +
                " expressions listed below, if applicable, shall have the following meanings;\n" +
                "a) \"Access Code(s)\" means any authentication mode as approved, specified by the Lender including" +
                " without limitation combination of username and password.\n" +
                "b) \"Account\" means the bank account where the Loan disbursement is requested and more specifically" +
                " provided under the Application Form for EMI/FMI products, and for e-voucher Loans the Borrower's" +
                " mobile number and email id shall be taken into consideration for the purpose of \"Account\"\n" +
                "c) \"Application Form\" means the loan application form submitted by the Borrower to the Lender for" +
                " applying and availing of the Facility, together with all other information, particulars, clarifications and" +
                " declarations, if any, furnished by the Borrower or any other persons from time to time in connection with" +
                " the Facility;\n" +
                "d) \"Business Day\" means a day (other than a Saturday or a Sunday) on which banks are open for general" +
                " business in Bengaluru;\n" +
                "e) \"Due Date\" means such date(s) on which any payment becomes due and payable under the terms of" +
                " the Transaction Documents (or otherwise);\n" +
                "f) \"Facility\" means the Loan applied by the Borrower and shall include a prospective Loan applied under" +
                " the credit line that may be provided by the Lender to the Borrower;\n" +
                "g) \"Increased Costs\" means\n" +
                "   (i) a reduction in the rate of return from the Loan(s) or on the Lender's overall capital (including as a" +
                " result of any reduction in the rate of return on capital brought about by more capital being required to be" +
                " allocated by the Lender)\n" +
                "   (ii) any additional or increased cost including provisioning as may be required under or as may be set" +
                " out in RBI regulations or any other such regulations from time to time; or\n" +
                "   (iii) a reduction of any amount due and payable under the Transaction Documents;\n" +
                "h) \"Sanctioning Authority\" includes the Reserve Bank of India.\n" +
                "i) \"Credit Limit\" means the maximum drawdown limit granted by the Lender (at its sole discretion) to the" +
                " Borrower as per this Transaction Document, which may be available to the Borrower as a revolving credit." +
                " Credit Line shall be construed as a part of the Facility and be governed under the terms of this" +
                " Transaction Document.\n" +
                "j) \"Prepayment Charges\" The amount equivalent to the difference between New Outstanding Balance and" +
                " the Existing Outstanding Balance shall be paid as prepayment charges by the Borrower in case of" +
                " prepayment of any instalment/ part prepayment of the Loan.  For the purpose of this definition \"New" +
                " Outstanding Balance\" shall mean the Outstanding Balance remaining due under the Loan pursuant to" +
                " and post prepayment of any instalment under the Loan and \"Existing Outstanding Balance\" shall mean" +
                " the Outstanding Balance which was remaining due to be paid under the Loan prior to prepayment of the" +
                " relevant instalment under the Loan, as reflected under the repayment schedule provided by the Lender" +
                " and \"Outstanding Balance\" shall mean collectively the principal, interest, compound interest, default" +
                " charges/ interest, any other charges, dues and monies payable, costs and expenses, reimbursable, as" +
                " outstanding from time to time and whether any of them are due or not in relation to the Loan.";

        Paragraph paragraph3 = new Paragraph(definitions, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);
    }

    private void addInterpretations(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("2. Interpretation", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String interpretations = "Capitalized terms used in these Standard Terms but not defined herein, shall have the meaning ascribed" +
                " to such terms under the Application Form.";

        Paragraph paragraph3 = new Paragraph(interpretations, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

    }

    private void addSanctionAndDisbursement(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("3. Sanction and Disbursement", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String sanctionsAndDisbursement = "3.1. The Lender may agree to grant the Facility to the Borrower on the basis of the information and" +
                " representations provided in the Application Form and other Transaction Documents. The Lender shall" +
                " provide a written acceptance to the request of the Borrower as contained in the Application Form or any" +
                " other Transaction Documents and by disbursement of a Loan (or a part thereof) requested thereunder by" +
                " the Borrower. Grant of the Facility and acceptance of the Borrower's request shall be at the absolute" +
                " discretion of the Lender and the Lender shall not be required to notify any rejection of the Application" +
                " Form to the Borrower. The Borrower may request for disbursement only if (a) no Event of Default or" +
                " potential event of default has occurred or is continuing, and (c) no material adverse event in the opinion of" +
                " the Lender has occurred.\n\n" +
                "3.2. The Borrower's request for the Facility under the Application Form shall be irrevocable unless" +
                " rejected by the Lender.\n\n" +
                "3.3. In the event that the Lender accepts the Borrower's request for the Facility and sanctions the Facility," +
                " the Lender may, subject to satisfaction of all the conditions precedents, disburse Loans into the Account" +
                " and the Borrower confirms that the Loan shall be utilized only for the Purpose and subject to the terms" +
                " under the Transaction Documents. Any such disbursement made by the Lender into the Account" +
                " (whether in the name of the Borrower or any third party) shall be a Loan. Lender shall not be responsible" +
                " for any dispute between Borrower and any such third party.\n";

        Paragraph paragraph3 = new Paragraph(sanctionsAndDisbursement, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph3, 1);
        document.add(paragraph3);
    }

    private void addInterestAndOtherCharges(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("4. Interest and other charges", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String interestAndOtherCharges = "4.1.  The Loan under the Facility shall carry interest at the rate specified in the Transaction Documents.\n" +
                "4.2. In case of an Event of Default, Borrower will, to the extent permitted by law, be required to pay" +
                " interest (before as well as after judgment / award) and such other charges plus GST (as applicable)" +
                " mentioned in this Applicable Form on the overdue amount to the other party on demand, for the period" +
                " from (and including) the original Due Date for payment to (but excluding) the date of actual payment, at" +
                " the Default Rate.\n\n" +
                "4.3. The Borrower acknowledge and agree that (i) the rates of interest specified in the Transaction" +
                " Documents are reasonable and that they represent genuine pre-estimates of the loss expected to be" +
                " incurred by the Lender in the event of non-payment of any monies by the Borrower; and (ii) the Rate of" +
                " Interest payable by the Borrower shall be subject to change prospectively based on the monetary policies" +
                " as may be changed by the Reserve Bank of India and other factors impacting the interest rates.\n\n" +
                "4.4. In case the Borrower wishes to prepay the Loan before the Due Date, such prepayment will be" +
                " subject to prepayment charges as mentioned in the summary of the Loan Terms and in the MITC, as" +
                " applicable to such prepayment. It is clarified that the Rate of Interest shall be charged for the full Tenure" +
                " of the Loan including unexpired Tenure under each Facility";

        Paragraph paragraph3 = new Paragraph(interestAndOtherCharges, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);
    }

    private void addPayments(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("5. Payments:", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String payments = "5.1. The Borrower shall make each payment under the Transaction Documents on or before the" +
                " respective Due Date. No Due Date shall exceed the Tenure of the Facility.\n\n" +
                "5.2. If the respective Due Date is not a Business Day, then the Borrower agrees that the payment shall be" +
                " made on the preceding Business Day.\n\n" +
                "5.3. All payments shall be made in freely transferable funds without any set-off, counterclaim or any" +
                " deduction. The Borrower shall not deduct/withhold any tax at source from the payment to be made to the" +
                " Lender. In case wherein the borrower is required to deduct any taxes then prior information to be" +
                " submitted to Lender.\n\n" +
                "5.4. Notwithstanding anything to the contrary, the Lender may, at any time, without assigning any reason," +
                " the undisbursed portion of the Facility and can also recall any or all portion of the disbursed Loan on" +
                " demand in the event of occurrence of an Event of Default. Upon such recall, the Loan and other amounts" +
                " stipulated by the Lender shall be payable forthwith.\n\n\n" +
                "5.5. The Borrower shall make repayment of the principal amount under the Loan in such proportion and" +
                " periodicity as may be provided in the Transaction Documents or as communicated by the Lender from" +
                " time to time.\n\n" +
                "5.6. The Borrower may, subject to payment of Prepayment Charges, prepay the outstanding principal" +
                " amounts of any of the Loan in full before the Due Date.\n\n" +
                "5.7. If the Borrower fails to pay any amount payable under this Facility on the Due Date, the Borrower" +
                " shall be liable to pay Platform Late Payment Charges and applicable interest on the overdue amount from" +
                " the Due Date up to the date of repayment of all the amounts as per the Rate of Interest of the Facility" +
                " mentioned in this Agreement. Any applicable interest accruing under this Clause shall be adjusted in the" +
                " already overdue EMI/ FMI and shall be due and payable with the EMI/ FMI amount.";

        Paragraph paragraph3 = new Paragraph(payments, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);
    }

    private void addRepresentationsAndWarranties(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("6. Representations and Warranties:", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String representationsAndWarranties = "6.1 The Borrower makes the representations and warranties set out in this Section 6.1 to the Lender, in" +
                " reliance of which the Lender may grant the Facility:\n\n" +
                "i.The Borrower has the competence and has obtained all authorizations (which is in full force and effect)" +
                " to enter into and perform under the Transaction Documents and to carry on its business and operations" +
                " as it is being or is proposed to be conducted;\n" +
                "ii. The Borrower is a resident Indian;\n" +
                "iii. The Facility once granted by the Lender under Transaction Documents constitutes legal, valid and" +
                " binding obligations of the Borrower enforceable in accordance with their respective terms;\n" +
                "iv. The Borrower is in compliance with all laws (including laws relating to environment, social and labour," +
                " anti-corruption and anti-money laundering) applicable to the Parties\n" +
                "v. The entry into, delivery and performance by the Borrower of, and the transactions contemplated by the" +
                " Transaction Documents, do not and will not conflict: (a) with any law; and (b) with any document which is" +
                " binding upon the Borrower or on any of its assets;\n" +
                "vi. The Borrower has a valid agreement, engagement or arrangement with the Platform which is currently" +
                " subsisting, and the Platform has not blacklisted, delisted, suspend or otherwise terminated the" +
                " arrangement;\n" +
                "vii. Where the accounts are required to be audited under applicable law, the most recent audited" +
                " accounts of the Borrower: (a) have been prepared in accordance with applicable accounting principles" +
                " and practices generally accepted and consistently applied; (b) have been duly audited by the auditors in" +
                " accordance with applicable laws (c) represent a true and fair view of its financial condition as at the date" +
                " to which they were drawn up, and there has been no material adverse effect since the date on which" +
                " those accounts were drawn up;\n" +
                "viii. Except to the extent disclosed to the Lender, no litigation, arbitration, administrative or other" +
                " proceedings are pending or threatened against the Borrower or its assets, which, if adversely determined," +
                " might have a material adverse effect;\n" +
                "ix. All information communicated to or supplied by or on behalf of the Borrower to the Lender from time to" +
                " time, are true and fair/ true, correct and complete in all respects as on the date on which it was" +
                " communicated or supplied; and (b) Nothing has occurred since the date of communication or supply of" +
                " any information to the Lender which renders such information untrue or misleading in any respect;\n" +
                "x. The Borrower is not a specially designated national or otherwise sanctioned, under sanctions (and" +
                " related laws) promulgated by any Sanctioning Authority; and\n" +
                "xi. The Borrower has not taken any action and no other steps have been taken or legal proceedings" +
                " started by or against it in any court of law/ other authorities for its insolvency, bankruptcy, winding up," +
                " dissolution, administration or re-organization or for the appointment of a receiver, administrator," +
                " administrative receiver, trustee or similar officer of the Borrower or of any or all of its assets.\n" +
                "xii. The Borrower is not a Politically Exposed Person (PEP). PEP are individuals who are or have been" +
                " entrusted with prominent public functions in a foreign country.\n\n" +
                "6.2. Each of the representations set out in Section 6.1 shall be deemed to be repeated on each day" +
                " during the Tenure of the Facility";

        Paragraph paragraph3 = new Paragraph(representationsAndWarranties, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);
    }

    private void addCovenants(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("7. Covenants:", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String covenants = "7.1. The Borrower shall provide all payment mandates including but not limited to electronic clearing" +
                " service (ECS) or national automated clearing house (NACH) mandate, as and when demanded by the" +
                " Lender or by the Platform.\n\n" +
                "7.2. Borrower shall ensure that all payment mandates including electronic clearing service (ECS) or" +
                " national automated clearing house (NACH) mandate, if any, provided to the Lender or to the Platform or" +
                " to any person nominated by the Lender, are honoured at all times and such mandates are not altered or" +
                " amended without prior permission of the Lender.\n\n" +
                "7.3. Borrower shall permit and facilitate inspection and audit of Borrower's premises, books and" +
                " statements of accounts and other documents as maybe required by the Lender, for the purposes of the" +
                " Facility.\n\n" +
                "7.4. The Borrower shall maintain its existence and shall carry on its business and operations in" +
                " compliance with all applicable laws (including laws relating to environment, social and labour," +
                " anti-corruption and anti-money laundering) applicable to the Parties and with due diligence and efficiency" +
                " and in accordance with sound technical, financial and managerial standards and business practices.\n\n\n" +
                "7.5. The Borrower shall ensure that the obligations under the Transaction Documents shall at least rank" +
                " pari-passu with all its unsecured and unsubordinated obligations.\n\n" +
                "7.6. The Borrower shall, within 3 (three) Business Days of demand by the Lender, pay the amount of any" +
                " Increased Costs incurred by the Lender as a result of (i) the introduction of or any change in (or in the" +
                " interpretation, administration or application of ) any law or regulation; (ii) compliance with any law or" +
                " regulation made before or after the date of relevant Loan (including any law or regulation concerning" +
                " capital adequacy, prudential norms, liquidity, reserve assets or tax) or  (ii) on account of factors beyond" +
                " the control of the Lender.\n" +
                "7.7. The Borrower agrees that it shall indemnify and hold harmless the Lender, to the fullest extent" +
                " permitted by applicable law, for all losses and liabilities (including due to claims by a third party), incurred" +
                " by the Lender as a result of any breach by him/her of any Transaction Documents.\n\n" +
                "7.8. Borrower shall submit the details of financials, sales details, stock and book debts statement on such" +
                " periodicity as required by the Lender.\n\n" +
                "7.9. Borrower shall promptly provide upon request of the Lender any further document/information as may" +
                " be required by the Lender and bear the stamp duty charges (if any).\n\n" +
                "7.10. Borrower undertakes to ensure that all information provided in the Application Form(s) shall remain" +
                " true at all times during the Tenure of the Facility.\n\n" +
                "7.11. Borrower shall indemnify for the misuse of funds/product/services availed from the Lender." +
                " Borrower shall use the funds legitimately Purpose only.\n\n" +
                "7.12. The Borrower shall not:\n" +
                "i. use the fund for the purchase of gold in any form, (including primary gold, gold bullion, gold jewellery," +
                " gold coins, units of gold exchange-traded funds (ETF) and units of gold mutual funds).\n" +
                "ii. directly or indirectly: (a) use the Facility in any transaction with or for the purpose of financing the" +
                " activities of, any person/country currently subject to any sanctions by Sanctioning Authority; and (b) take" +
                " part in or financing any activity, production, use of, trade in, distribution of, or otherwise involved in any" +
                " exclusion-list; and\n" +
                "iii. directly or indirectly, make or offer any payment, gift or other advantage which is intended to, or does," +
                " influence or reward any person (whether or not they are in the public sector) for acting in breach of an" +
                " expectation of good faith, impartiality or trust or otherwise performing their function improperly.\n" +
                "iv. use the funds to invest in any real estate activities, capital market, equity market, and to repay any" +
                " personal loan/ housing loan/ rupee loan or use of the funds for working capital or general corporate" +
                " purposes.\n\n" +
                "7.13. The Borrower shall provide end-use certificate in a form and manner satisfactory to the Lender.\n\n" +
                "7.14. The Borrower shall promptly notify the Lender in writing upon occurrence of any breach of Covenant" +
                " or representation or occurrence of Event of Default and the steps, if any, being taken to remedy it.\n\n" +
                "7.15. The Borrower shall from time to time, if required by the Lender, provide additional security, in a form" +
                " and manner satisfactory to the Lender.\n\n" +
                "7.16. The Borrower shall promptly notify the Lender of any breach of any representations, warranties," +
                " covenants, undertakings or any other terms of these Standard Terms together with the steps taken to" +
                " remedy it. Upon the breach being reported, the Lender may, without prejudice to any of its rights under" +
                " law or contract, in its sole discretion recommend implementation of corrective measures to remedy such" +
                " breach in a form, manner and time as may be necessary or desirable to the Lender.\n\n" +
                "7.17. The Borrower shall ensure that throughout the Tenure of the Facility a valid agreement," +
                " engagement or arrangement with the Platform shall subsist and the Platform has not" +
                " blacklisted/delisted/suspended or otherwise terminated such an arrangement. This shall be considered an" +
                " event of default for the purposes of the Loan.\n\n" +
                "7.18. Notwithstanding any of the provisions of the Indian Contract Act, 1872 or any other applicable law or" +
                " anything contained in the Transaction Documents, the amounts repaid by the Borrower shall be" +
                " appropriated first towards cost, charges and expenses and other monies; secondly towards interest on" +
                " cost charges and expenses and other monies; thirdly towards interest on the delayed payments; fourthly" +
                " towards interest payable under the Transaction Documents and lastly towards repayment of any principal" +
                " amounts.";

        Paragraph paragraph3 = new Paragraph(covenants, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);
    }

    private void addEventOfDefault(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("8. Event of Default:", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String eventOfDefault = "8.1. The Borrower shall be deemed to have committed default on the occurrence of, inter-alia but not" +
                " limited to, any one or more of the following events (hereinafter referred to as \"Event of Default\"):\n\n" +
                "i. Default has occurred in the payment of any monies in respect of the Facility (whether at stated Due" +
                " Date, by acceleration or otherwise) under the terms of the Transaction Documents.\n" +
                "ii. Default (other than a payment default) has occurred in the performance of any covenant, condition," +
                " agreement or obligation on the part of the Borrower under the Transaction Documents and such default" +
                " has continued for a period of 10 (ten) days after notice in writing thereof has been given to the Borrower" +
                " or as the case may be, to such other person, by the Lender (except where the Lender is of the opinion" +
                " that such default is incapable of remedy, in which event, no notice shall be required).\n" +
                "iii. The Borrower has, or there is a reasonable apprehension that the Borrower would, voluntarily or" +
                " involuntarily become the subject of proceedings under any bankruptcy or insolvency law, or is voluntarily" +
                " or involuntarily dissolved, or declared insolvent, or if the Borrower has taken or suffered to be taken any" +
                " action for its re- organization, liquidation or dissolution or if a receiver or liquidator or a similar official has" +
                " been appointed or allowed to be appointed in respect of all or any part of the assets of the Borrower or if" +
                " an attachment or distrait has been levied on the Borrower's assets or any part thereof or certificate" +
                " proceedings have been taken or commenced for recovery of any dues from the Borrower or if one or" +
                " more judgments or decrees have been rendered or entered against the Borrower and such judgments or" +
                " decrees are not vacated, discharged or stayed for a period of 30(thirty) days, and such judgments or" +
                " decrees involve in the aggregate, a liability which could have a material adverse effect.\n" +
                "iv. Death of any Borrower.\n" +
                "v. Breach of any representation, warranty, declaration or confirmation made or deemed to be made under" +
                " the Transaction Documents.\n" +
                "vi. The Borrower is unable or has admitted in writing its inability to pay any of its indebtedness as and" +
                " when they mature or become due.\n" +
                "vii. If the Borrower ceases or threatens to cease to carry on any of its businesses in its current form which" +
                " could have a material adverse effect.\n" +
                "viii. The security, if any, for the Facility is in jeopardy or ceases to have effect.\n" +
                "ix. It is or becomes unlawful for any Borrower to perform any of its obligations under the Transaction" +
                " Documents.\n\n" +
                "8.2. An event of default howsoever described (or any event which with the giving of notice, lapse of time," +
                " determination of materiality or fulfilment of any other applicable condition or any combination of the" +
                " foregoing would constitute an event of default) occurs under any agreement or any indebtedness of the" +
                " Borrower or becomes capable at such time of being declared, due and payable under such agreements" +
                " before it would otherwise have been due and payable.\n\n" +
                "8.3. One or more events, conditions or circumstances (including any change in law) shall occur or exist" +
                " which could have a material adverse effect.\n\n" +
                "8.4. The Borrower shall promptly notify the Lender in writing upon becoming aware of any default and the" +
                " steps, if any, being taken to remedy it.";

        Paragraph paragraph3 = new Paragraph(eventOfDefault, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

    }

    private void addConsequencesOfEventOfDefault(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("9. Consequences of Event of Default:", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String consequencesOfEventOfDefault = "9.1. Upon occurrence of any Event of Default, the Lender shall be entitled at its absolute discretion to" +
                " inter alia:\n\n" +
                "i. Call upon the Borrower to pay forthwith the outstanding balance of the Facility together with interest and" +
                " all sums payable by the Borrower to the Lender;\n" +
                "ii. Call upon the Borrower to pay all claims, costs, losses and expenses that may be incurred by the" +
                " Lender because of any act or default on the part of the Borrower with respect to the Facility and/or for the" +
                " recovery of the outstanding dues (including legal/attorney fee) and/or on account of failure of the" +
                " Borrower of any of the terms and conditions under the Transaction Documents;\n" +
                "iii. Enforce any rights available to it under any law or contract";

        Paragraph paragraph3 = new Paragraph(consequencesOfEventOfDefault, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

    }

    private void addMiscellaneous(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("10. Miscellaneous:", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String miscellaneous = "10.1.  Online Transactions:\n\n" +
                "i. For ease of operation of the Borrower, Borrower shall have the option of applying for further facilities" +
                " provided by the Lender using online secure platforms as may be specified by the Lender (hereinafter" +
                " referred to as \"Online Facility\"). The Facility shall be extended to the Borrower subject to the Borrower" +
                " complying with the Lender's credit parameters and submitting all documents/information as may be" +
                " required by Lender in such form as may be specified by the Lender from time to time. The Lender may in" +
                " its sole discretion reject the application for the Facility/loan by the Borrower.\n" +
                "ii. It shall be the sole responsibility of the Borrower to ensure that the Access Codes are not compromised" +
                " or shared with any unauthorized users.\n" +
                "iii. The Borrower expressly agrees and acknowledges to have read and understood the terms applicable" +
                " for usage of the Online Facility and be bound by such terms and conditions (as amended by the Lender" +
                " from time to time)at all times during the tenure of such Facility.\n" +
                "iv. The Lender shall have no obligation to verify the authenticity of any transaction/instruction received or" +
                " purported to have been received from the Borrower through the Online Facility or purporting to have been" +
                " sent by the Borrower other than by means of verification of the Access Codes.\n" +
                "v. All the records of the Lender with respect to the online request for facility arising out of the use of the" +
                " Online Facility shall be conclusive proof of the genuineness and accuracy of the transaction. While the" +
                " Lender and its affiliates shall endeavour to carry out the instructions promptly, they shall not be" +
                " responsible for anydelay in carrying on the instructions due to any reason whatsoever, including due to" +
                " failure of operational systems or any requirement of law.\n" +
                "vi. Borrower can check the availability of a pre-approved offer that may be made by the Lender through" +
                " Online Facility. Any pre-approved offer by the Lender does not constitute grant of facility to the Borrower" +
                " and shall be subject to the terms as may be specified by Lender from time to time" +
                "vii. Borrower acknowledges and accepts that the Lender may permit/allow anybody quoting the correct" +
                " Access Codes and other details to conduct the type of operations which are permitted under the Online" +
                " Facility.\n\n" +
                "10.2. Notices\n\n" +
                " Any notice or request to be given or made by a party to the other shall be in writing. Such notice or" +
                " request shall be deemed to have been duly received by the party to whom it is addressed if it is given or" +
                " made at the address specified below or at such other address as may be agreed from time to time:\n\n" +
                " For the Lender: 3rd Floor, No.128/9, Maruthi Sapphire, HAL Airport Road, Murgesh Palya, Bangalore KA" +
                " 560017 INDIA.\n" +
                " For the Borrower: The address as stated in the Application Form. The Lender may also agree to act on" +
                " the basis of request made via registered email ID of the Borrower.\n\n" +
                " Provided however that a notice or communication to any Borrower shall be deemed to be a notice or" +
                " communication to other Borrower(s).\n\n" +
                "10.3. Any and all claims and disputes arising out of or in connection with the Transaction Documents or" +
                " its performance shall be subject to the laws of India and shall be settled by arbitration by a single" +
                " arbitrator to be appointed by the Lender. The seat of arbitration shall be in Bangalore and the language," +
                " English. The arbitration shall be conducted under the provisions of the Arbitration and Conciliation Act," +
                " 1996 or any statutory modification or re-enactment thereof for the time being in force and the award of" +
                " such arbitrator shall be final and binding upon the Borrower and the Lender. Subject to the foregoing, the" +
                " courts of Bangalore shall have the exclusive jurisdiction on all claims or disputes arising under any of the" +
                " Transaction Document.\n\n" +
                "10.4. The Lender shall, without prejudice to any of its specific rights under any other agreements with the" +
                " Borrower, at its sole discretion, be at liberty to apply any other money, amounts, securities and other" +
                " property of the Borrower (whether singly or jointly with another or others) in possession of the Lender or" +
                " any of its subsidiary/ affiliate/ associate company in or towards payment of the dues under Facility" +
                " granted under the Transaction Documents. The borrower can avail Online Facility on the Platform.\n\n" +
                "10.5. The Lender shall be entitled at the sole risk and cost of the Borrower to engage one or more" +
                " person(s) to collect the Borrower's dues and shall further be entitled to share such information, facts and" +
                " figures pertaining to the Borrower as the Lender deems fit. The Lender may also delegate to such" +
                " person(s) the right and authority to perform and execute all such acts, deeds, matters and things" +
                " connected herewith, or incidental thereto, as the Lender may deems fit. The Borrower recognizes," +
                " accepts and consents to such delegation.\n" +
                "10.6. The Lender shall have the right to disclose or publish any information regarding the Borrower or" +
                " guarantor(s) (if any) and any information and documents that they might possess from time to time to:\n\n" +
                "i. any of its branches or with other banks, financial institutions, Credit Information Bureau of India Limited," +
                " credit reference or rating agencies/bureaus or other individuals/entities either in response to their credit" +
                " inquiries directed to the Lender or in the event of the Borrower not complying with any terms and" +
                " conditions herein or otherwise;\n" +
                "ii. the Reserve Bank of India and/or any other statutory authority or official of the Government of India or" +
                " that of any other state.\n\n" +
                "10.7. The Borrower shall not assign or transfer all or any of its rights, benefits or obligations under the" +
                " Transaction Documents. Borrower expressly acknowledges and agrees that Lender may, at any time," +
                " without requiring the prior consent from the Borrower or any other person and without giving notice to the" +
                " Borrower or any other person, sell, transfer, assign, securitise, novate, part with any or all of its" +
                " receivables arising in relation to the Facility and its rights and benefits and obligations (if any) under all or" +
                " any of the Transaction Documents, to any third party (\"Assignee\"), in any manner whatsoever including" +
                " by direct assignment or by the process of securitisation. Borrower irrevocably and unconditionally" +
                " confirms that it shall continue to be bound by the terms herein and other Transaction Documents" +
                " notwithstanding such transfer or assignment by Lender and that the Assignee shall acquire an interest in" +
                " the Transaction Documents forthwith.\n\n" +
                "10.8. In case of default committed by the Borrower, the Lender may also disclose and publish the" +
                " information about the Borrower and its default with the Lender in the public domain including through" +
                " social media.\n\n" +
                "10.9. The Borrower acknowledges that the Lender has or may have business and other transactions with" +
                " third parties (including those who are in the business of manufacturing, supplying or otherwise dealing" +
                " with any asset being financed by the proceeds of this Facility) and hereby waives any conflict of interest" +
                " that it may have on such an arrangement. Further, the Borrower acknowledges that any contract or" +
                " arrangement between the Lender and such third parties are independent of these Standard Terms\n\n" +
                "10.10. The Lender reserves the right to amend the terms of these Standard Terms (except amendment to" +
                " Rate of Interest) by intimating the same to the Borrower. Rate of Interest shall not be changed without" +
                " prior consent of the Borrower.\n\n" +
                "10.11 The Lender shall be entitled to set-off all monies, securities, deposits and other assets and" +
                " properties belonging to the Borrowers and/or the Guarantor(s) in the possession of the Lender, whether" +
                " in, or on any account of the Lender or otherwise, whether held singly or jointly by the Borrowers with" +
                " others and may appropriate the same.\n\n" +
                "10.12 GST: All the charges and fees mentioned in this Agreement shall be subject to applicable GST as" +
                " per applicable GST laws. Any Borrower who is not registered under Goods and Service Tax Act (GST)" +
                " shall not be eligible to claim input of GST paid on charges levied. In case the Borrower is registered under" +
                " Goods and Service Tax Act and want to avail GST input, then please connect with the Platform.";

        Paragraph paragraph3 = new Paragraph(miscellaneous, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

        LineSeparator underline = new LineSeparator();
        underline.setOffset(-2);
        underline.setPercentage(100);
        underline.setLineColor(BaseColor.BLACK);
        document.add(new Chunk(underline));

        String miscellaneous2 = "For the purpose of this clause, the term 'GST' or 'GST law' shall include the Central Goods and Services" +
                " Tax ('CGST'), the State Goods and Services Tax ('SGST'), Integrated Goods and Services Tax ('IGST')," +
                " Union Territory Goods and Services Tax ('UTGST') and any other taxes levied under the GST related" +
                " legislations in India as may be applicable. The term 'GST legislation/s' should be accordingly interpreted.";

        Paragraph paragraph4 = new Paragraph(miscellaneous2, HELVETICA_SMALL);
        paragraph4.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph4);

    }

    private void addGrievanceRedressalMechanismOfThePlatform(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("11.Grievance Redressal Mechanism of the Platform:", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String grievanceRedressalMechanismOfThePlatform = "Borrower can raise their concerns pertaining to the Platform, EMI/ FMI schedule, Facility Type," +
                " Processing Fee and/ or any other charges or any other concern related to the product to authorised" +
                " representatives of  Finnovation Tech Solutions Private Limited as below. Please refer to" +
                " https://www.xxxxxxx.in/grievance-redressal for the updated  Grievance Redressal Policy information.\n\n";

        Paragraph paragraph3 = new Paragraph(grievanceRedressalMechanismOfThePlatform, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

        Paragraph paragraph4 = new Paragraph("  > Grievance Redressal Officer", HELVETICA_SMALL_BOLD);
        paragraph4.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph4, 1);
        document.add(paragraph4);

        String grievanceRedressalOfficer = "Borrowers are requested to address all their grievances at the first instance to the Grievance Redressal" +
                " Officer. The contact details of the Grievance Redressal Officer are:\n\n" +
                " Mr xxxxx Kumar\n" +
                " Company: xxxxx Tech Solutions Private Limited\n" +
                " Address: 5th Floor, xxxx, xxxx,\n" +
                "               xxxxx, Bengaluru, 56xxx16\n" +
                " Contact: 804429xxxx\n" +
                " Email: help@xxxx.in\n\n" +
                " The Grievance Redressal Officer may be reached on the number provided above anytime between 10:00" +
                " to 21:00 from Monday to Friday and 10:00 to 19:00 on Saturdays except pubic holidays or through the" +
                " e-mail address above. The Grievance Redressal Officer shall endeavour to resolve the grievance within a" +
                " period of (14) fourteen days from the date of receipt of a grievance.\n\n";

        Paragraph paragraph5 = new Paragraph(grievanceRedressalOfficer, HELVETICA_SMALL);
        paragraph5.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph5);

        Paragraph paragraph6 = new Paragraph("  > Nodal Officer", HELVETICA_SMALL_BOLD);
        paragraph4.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph6, 1);
        document.add(paragraph6);

        String nodalOfficer = "If the Borrower does not receive a response from the Grievance Redressal Officer within 14 (fourteen)" +
                " days of making a representation, or if the Borrower is not satisfied with the response received from the" +
                " Grievance Redressal Officer, the Borrower may reach the Nodal Officer on the number below anytime" +
                " between 10:00 to 21:00 from Monday to Friday and 10:00 to 19:00 on Saturdays except pubic holidays or" +
                " write to the Nodal Officer at the e-mail address below.Â  The contact details of the Nodal Officer are" +
                " provided below.\n\n" +
                " Mr xxxx Kumar\n" +
                " Designation: Chief Operating Officer\n" +
                " Company: xxxx Tech Solutions Private Limited\n" +
                " Address: 3rd Floor, No. 128/9, xxxx, xxxx Road,\n" +
                "             Bangalore - 56xxx7\n" +
                " Contact: 804429xxxx\n" +
                " Email: grievance@xxxx.in";

        Paragraph paragraph7 = new Paragraph(nodalOfficer, HELVETICA_SMALL);
        paragraph7.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph7);

    }

    private void addGrievanceRedressalMechanismOfTheLender(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("12. Grievance Redressal Mechanism of the Lender", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String grievanceRedressalMechanismOfTheLender = "For all grievances against the against the Lender i.e. Krazybee Services Private Limited, please refer to" +
                " https://www.xxxxfc.in/grievance-policyfor the updated Grievance Redressal Policy information. Further," +
                " for your convenience details of the Grievance redressal mechanism of the Lender is provided" +
                " hereinbelow\n\n";

        Paragraph paragraph3 = new Paragraph(grievanceRedressalMechanismOfTheLender, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

        Paragraph paragraph4 = new Paragraph("  > Grievance Redressal Officer", HELVETICA_SMALL_BOLD);
        paragraph4.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph4, 1);
        document.add(paragraph4);

        String grievanceRedressalOfficer = "Borrowers are requested to address all their grievances at the first instance to the Grievance Redressal" +
                " Officer. The contact details of the Grievance Redressal Officer are:\n\n" +
                " Mr xxxx Kumar\n" +
                " Address: 3rd Floor, No. 128/9, xxxx Sapphire, xxxx Airport Road,\n" +
                "                xxxx, Bangalore - 56xxx7\n" +
                " Contact: 804429xxxx\n" +
                " Email: reachus@xxxxfc.in\n\n" +
                " The Grievance Redressal Officer may be reached on the number provided above anytime between 10:00" +
                " and 19:00 or through the e-mail address above. The Grievance Redressal Officer shall endeavour to" +
                " resolve the grievance within a period of 14 days from the date of receipt of a grievance\n\n";

        Paragraph paragraph5 = new Paragraph(grievanceRedressalOfficer, HELVETICA_SMALL);
        paragraph5.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph5);

        Paragraph paragraph6 = new Paragraph("  > Nodal Officer", HELVETICA_SMALL_BOLD);
        paragraph6.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph6, 1);
        document.add(paragraph6);

        String nodalOfficer = "If the Borrower does not receive a response from the Grievance Redressal Officer within 14 (fourteen)" +
                " days of making a representation, or if the Borrower is not satisfied with the response received from the" +
                " Grievance Redressal Officer, the Borrower may reach the Nodal Officer on the number below anytime" +
                " between 10:00 to 21:00 from Monday to Friday and 10:00 to 19:00 on Saturdays except pubic holidays or" +
                " write to the Nodal Officer at the e-mail address below.Â  The contact details of the Nodal Officer are" +
                " provided below.\n\n" +
                " Mr xxxx Kumar\n" +
                " Designation: Chief Operating Officer\n" +
                " Address: 3rd Floor, No. 128/9, xxxx, xxxx Road,\n" +
                "             Bangalore - 56xxx7\n" +
                " Contact: 804429xxxx\n" +
                " Email: grievance@xxxx.in\n\n";

        Paragraph paragraph7 = new Paragraph(nodalOfficer, HELVETICA_SMALL);
        paragraph7.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph7);

        Paragraph paragraph8 = new Paragraph("  > Complaints to Ombudsman", HELVETICA_SMALL_BOLD);
        paragraph8.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph8, 1);
        document.add(paragraph8);

        String complaintsToOmbudsman = "In case the Borrower does not receive a response from the Grievance Redressal Official or the Nodal" +
                " Officer within one month from the date of making a representation to the Lender, or if the Borrower is not" +
                " satisfied with the response so received, a complaint may be made in accordance with the 'The" +
                " Ombudsman Scheme for Non-Banking Financial Companies, 2018' (\"Ombudsman Scheme\") to the" +
                " Ombudsman in whose jurisdiction the office of the Lender complained against, is located. For contact" +
                " details of the Ombudsman and for salient features of the Ombudsman Scheme, please refer to Annexure- A of the Fair Practices Code adopted by the Company and available on our website" +
                " https://www.xxxxfc.in/fair-practice-code. A copy of the Ombudsman Scheme is available on the website" +
                " of the Reserve Bank of India at www.rbi.org.in and also with our Nodal Officer.";

        Paragraph paragraph9 = new Paragraph(complaintsToOmbudsman, HELVETICA_SMALL);
        paragraph9.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph9);

        Paragraph paragraph10 = new Paragraph();
        leaveEmptyLine(paragraph10, 17);
        document.add(paragraph10);

    }

    private void addAnnexureA(Document document, Loan loan, Customer customer) throws DocumentException {

        LoanType loanType = loanTypeRepository.findByRecordId(loan.getLoanType());

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("ANNEXURE A", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph2);

        Paragraph paragraph3 = new Paragraph("THE MOST IMPORTANT TERMS AND CONDITIONS - MITC", HELVETICA_SMALL_BOLD);
        paragraph3.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph3);

        Paragraph paragraph4 = new Paragraph();
        leaveEmptyLine(paragraph4, 1);
        document.add(paragraph4);

        String points1To3 = "1. We refer to the application form dated 2020-12-15 (\"Application Form\") for grant of the Loan described" +
                " below.\n" +
                "2. Capitalized terms used but not defined hereunder shall have the meaning ascribed to the term in other" +
                " Transaction Documents.\n" +
                "3. The Borrower acknowledges and confirms that the below mentioned are the most important terms and" +
                " conditions in the application for the Loan (and which would apply to the Borrower in respect of the Loan, if" +
                " the request for the Loan is accepted by the Lender) and they shall be read in conjunction with the" +
                " Application Form(s), and the Standard Terms):\n\n";

        Paragraph paragraph5 = new Paragraph(points1To3, HELVETICA_SMALL);
        paragraph5.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph5);

        String[][] tableData = {
                {"Borrower", customer.getName()},
                {"Facility Type", "Term Loan"},
                {"Max Amount Sanctioned (INR)", "Max Credit Line " + loan.getDesiredLoan()},
                {"PURPOSE OF LOAN", loanType.getName()},
                {"Tenure (months/ days)", loan.getTenure() + " months"},
                {"Rate of Interest (p.a.%)", loan.getInterestRate() + " %"},
                {"EMI/FMI Schedule", "Kindly refer to Annexure B"},
                {"Platform Late Payment Charges:", "Penalty charges applicable on repayment post due date " +
                        "for each instalment:\n" +
                        "First Overdue Day penalty charges 500 INR\n" +
                        "Penalty charges for 2-90 days 0.1 % of principal*\n" + "*round to nearest rupee"},
                {"Pre-Payment Charges", ""},
                {"Risk Category", "Low"}

        };

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new float[]{50f, 50f});

        Font boldFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
        Font normalFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);

        for (String[] row : tableData) {
            for (int i = 0; i < row.length; i++) {
                Font currentFont = (i == 0) ? boldFont : normalFont;
                PdfPCell cell = new PdfPCell(new Phrase(row[i], currentFont));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setMinimumHeight(25f);
                table.addCell(cell);
            }
        }
        document.add(table);

        Paragraph paragraph6 = new Paragraph();
        leaveEmptyLine(paragraph6, 1);
        document.add(paragraph6);

        String point4 = "4. The Borrower understands that the identical products with identical tenor and availed during the same" +
                " period may attract different interest rates for different customers. Interest rates could vary depending" +
                " upon consideration of all or combination of multiple factors including but not limited to the following:\n";

        Paragraph paragraph7 = new Paragraph(point4, HELVETICA_SMALL);
        paragraph7.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph7);

        Font bulletFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.BLACK);
        com.itextpdf.text.List bulletList = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        bulletList.setIndentationLeft(5);
        bulletList.setListSymbol(new Chunk("\u2022 ", bulletFont));

        bulletList.add(new ListItem("Credit and default risk in the related business segment"));
        bulletList.add(new ListItem("Historical performance of similar homogeneous clients"));
        bulletList.add(new ListItem("Profile of the applicant"));
        bulletList.add(new ListItem("Industry segment"));
        bulletList.add(new ListItem("Repayment track record of the applicant"));
        bulletList.add(new ListItem("Nature and value of collateral security"));
        bulletList.add(new ListItem("Secured Vs unsecured loan"));
        bulletList.add(new ListItem("Loan ticket size"));
        bulletList.add(new ListItem("Credit rating of the applicant"));
        bulletList.add(new ListItem("Loan tenor"));
        bulletList.add(new ListItem("Location delinquency and collection performance"));
        bulletList.add(new ListItem("Other indebtedness of the applicant"));

        document.add(bulletList);

        Paragraph paragraph8 = new Paragraph();
        leaveEmptyLine(paragraph8, 1);
        document.add(paragraph8);

        String point5To8 = "5. The Borrower understands that the Lender has adopted risk-based pricing, which is arrived by taking" +
                " into account, broad parameters like the customers financial and credit profile. Further, the Borrower" +
                " acknowledges and confirms that the Lender shall have the discretion to change prospectively the rate of" +
                " interest and other charges applicable to the Loan.\n" +
                "6. The Borrower acknowledges and confirms having received a copy of each Transaction Document and" +
                " agrees that this letter is a Transaction Document.\n" +
                "7. The Borrower herby grants a Credit of upto INR 150000 to the Borrower valid till 31 Dec 2023. \n" +
                "8. I understand and accept that no moratorium or deferment of EMI/ FMI will be provided by the Lender" +
                " (as per the Lender's policy on EMI Moratorium) on the Facility under this Application Form and there shall" +
                " be no demur or protest by me in this regard";

        Paragraph paragraph9 = new Paragraph(point5To8, HELVETICA_SMALL);
        paragraph9.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph9);

        Paragraph paragraph10 = new Paragraph();
        leaveEmptyLine(paragraph10, 23);
        document.add(paragraph10);

    }

    private void addAnnexureB(Document document) throws DocumentException {

        Paragraph paragraph1 = new Paragraph();
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("ANNEXURE B", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph2);

        Paragraph paragraph3 = new Paragraph();
        leaveEmptyLine(paragraph3, 1);
        document.add(paragraph3);

        Paragraph paragraph4 = new Paragraph("(Repayment Schedule)", HELVETICA_SMALL_BOLD);
        paragraph4.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph4);

        Paragraph paragraph5 = new Paragraph();
        leaveEmptyLine(paragraph5, 1);
        document.add(paragraph5);

    }

    private void addAnnexureBNoteAndAcknowledgement(Document document) throws DocumentException {

        Paragraph paragraph5 = new Paragraph();
        leaveEmptyLine(paragraph5, 1);
        document.add(paragraph5);

        String note = "Note: The due date, interest amount and repayable amount is subject to change as per the disbursement" +
                " date of the loan amount. An Annexure comprising repayment schedule will be sent to the Customer after" +
                " the disbursement date clearly highlighting details of repayments (subject to adjustments) which will" +
                " supersede the above Repayment Schedule and the same shall be acceptable to the Customer.\n\n";

        Paragraph paragraph2 = new Paragraph(note, HELVETICA_SMALL);
        paragraph2.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph2);

        String acknowledgement = "ACKNOWLEDGEMENT: Lender acknowledges receipt of your Application Form together with the" +
                " Standard Term. We will revert within 5 (five) working days subject to furnishing the necessary documents" +
                " to Lender's satisfaction.\n\n" + "CC details: ";

        Paragraph paragraph3 = new Paragraph(acknowledgement, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

        Paragraph paragraph4 = new Paragraph();
        leaveEmptyLine(paragraph4, 23);
        document.add(paragraph4);

    }

    public byte[] getImageBytes(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);

        try (InputStream is = url.openStream();
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096]; // Buffer for reading data
            int bytesRead;

            while ((bytesRead = is.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            return baos.toByteArray();
        }
    }

    private void addPanAadharProfileImages(Document document, Customer customer) throws DocumentException, IOException {

        byte[] imageBytes1 = getImageBytes(customer.getAadharFrontProof());
        byte[] imageBytes2 = getImageBytes(customer.getAadharBackProof());
        byte[] imageBytes3 = getImageBytes(customer.getPanProof());
        byte[] imageBytes4 = getImageBytes(customer.getProfileImage());

//        System.out.println("AadharFrontProof URL: " + customer.getAadharFrontProof());
//        System.out.println("Bytes length = " + imageBytes1.length);
//        System.out.println("First 50 bytes: " + Arrays.toString(Arrays.copyOf(imageBytes1, Math.min(imageBytes1.length, 50))));
//        System.out.println("As String: " + new String(imageBytes1, 0, Math.min(imageBytes1.length, 200)));

        Image image1 = Image.getInstance(imageBytes1);
        image1.scaleToFit(400, 400);
        image1.setAlignment(Image.ALIGN_LEFT);
        document.add(image1);
        Image image2 = Image.getInstance(imageBytes2);
        image2.scaleToFit(400, 400);
        image2.setAlignment(Image.ALIGN_LEFT);
        document.add(image2);
        Image image3 = Image.getInstance(imageBytes3);
        image3.scaleToFit(400, 400);
        image3.setAlignment(Image.ALIGN_LEFT);
        document.add(image3);
        Image image4 = Image.getInstance(imageBytes4);
        image4.scaleToFit(400, 400);
        image4.setAlignment(Image.ALIGN_LEFT);
        document.add(image4);

//        if (base64Image2 != null && !base64Image2.isEmpty()) {
//            byte[] imageBytes = Base64.getDecoder().decode(base64Image2);
//            Image image = Image.getInstance(imageBytes);
//            image.scaleToFit(400, 400);
//            image.setAlignment(Image.ALIGN_LEFT);
//            document.add(image);
//        } else {
//            document.add(new Paragraph("No image provided."));
//        }

    }

    private void addAnnexureB_PdfContents(Document document, Loan loan) throws DocumentException {

        Paragraph paragraph1 = new Paragraph("ANNEXURE B", HELVETICA_SMALL_BOLD);
        paragraph1.setAlignment(Element.ALIGN_CENTER);
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Paragraph paragraph2 = new Paragraph("(Repayment Schedule)", HELVETICA_SMALL_BOLD);
        paragraph2.setAlignment(Element.ALIGN_CENTER);
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        Paragraph paragraph3 = new Paragraph("This Annexure B forms an integral part of Loan ID " + loan.getRecordId(), HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

    }

    private void addAdditionalTermsAndConditions(Document document, Loan loan) throws DocumentException {

        Paragraph paragraph = new Paragraph();
        leaveEmptyLine(paragraph, 1);
        document.add(paragraph);

        Paragraph paragraph1 = new Paragraph(" Additional Terms and Conditions:", HELVETICA_SMALL_BOLD);
        paragraph1.setAlignment(Element.ALIGN_LEFT);
        leaveEmptyLine(paragraph1, 1);
        document.add(paragraph1);

        Font bulletFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.BLACK);
        com.itextpdf.text.List bulletList = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        bulletList.setIndentationLeft(5);
        bulletList.setListSymbol(new Chunk("\u2022 ", bulletFont));

        bulletList.add(new ListItem("This Repayment Schedule will be read in conjunction with the terms of the Loan Facility Agreement" +
                " bearing the Loan ID " + loan.getRecordId() + " entered with Shree Meenakshi Finance"));
        bulletList.add(new ListItem("The Loan Facility Agreement will be modified to the extent mentioned herein"));
        bulletList.add(new ListItem("All other terms and conditions of the Loan Facility Agreement will remain in full force and effect."));

        document.add(bulletList);

    }

    private void addTitleAndLogo(Document document) {

        Float[] logoImgScale = {5.0F, 5.0F};
        try (InputStream imageStream = getClass().getClassLoader().getResourceAsStream("static/images/icon.png")) {
            if (imageStream == null) {
                throw new IOException("Logo image not found in classpath");
            }
            Image img = Image.getInstance(org.apache.commons.io.IOUtils.toByteArray(imageStream));
            img.scalePercent(logoImgScale[0], logoImgScale[1]);
            img.setAlignment(Element.ALIGN_RIGHT);

            PdfPTable table = new PdfPTable(2);
            table.setWidthPercentage(100);
            table.setWidths(new float[]{80f, 20f});

            PdfPCell titleCell = new PdfPCell(new Phrase(reportFileName, HELVETICA));
            titleCell.setBorder(Rectangle.NO_BORDER);
            titleCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            titleCell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(titleCell);

            PdfPCell imageCell = new PdfPCell(img, false);
            imageCell.setBorder(Rectangle.NO_BORDER);
            imageCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            imageCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(imageCell);

            document.add(table);

        } catch (DocumentException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void addLoanPdfContents(Document document, String loanApplicationId) throws DocumentException {

        LoanApplication loanApplication = loanApplicationRepository.findByRecordId(loanApplicationId);
        Customer customer = customerRepository.findByRecordId(loanApplication.getCustomerId());
        LoanTemplate loanTemplate = loanTemplateRepository.findByRecordId(loanApplication.getLoanTemplateId());
        LoanType loanType = loanTypeRepository.findByRecordId(loanApplication.getLoanTypeId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
        String date = simpleDateFormat.format(new Date());
        String customerDetails = "Date: " + date + "\n" +
                "Dear " + customer.getName() + ",\n" +
                customer.getAddress();
        Paragraph paragraph1 = new Paragraph("Please read carefully", HELVETICA_SMALL_BOLD);
        paragraph1.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph1);

        PdfPTable table1 = new PdfPTable(3);
        table1.setWidthPercentage(100);
        table1.setWidths(new float[]{33.33f, 33.33f, 33.33f});

        PdfPCell titleCell = new PdfPCell(new Phrase(customerDetails, HELVETICA_SMALL));
        titleCell.setBorder(Rectangle.NO_BORDER);
        titleCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        titleCell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table1.addCell(titleCell);

        PdfPCell titleCell1 = new PdfPCell(new Phrase("", HELVETICA_SMALL_BOLD));
        titleCell1.setBorder(Rectangle.NO_BORDER);
        titleCell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        titleCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table1.addCell(titleCell1);
        document.add(table1);

        PdfPCell titleCell2 = new PdfPCell(new Phrase("", HELVETICA_SMALL_BOLD));
        titleCell2.setBorder(Rectangle.NO_BORDER);
        titleCell2.setHorizontalAlignment(Element.ALIGN_RIGHT);
        titleCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table1.addCell(titleCell2);

        document.add(table1);

        Paragraph paragraph2 = new Paragraph();
        leaveEmptyLine(paragraph2, 1);
        document.add(paragraph2);

        String line3 = "We refer to your Loan ID " + loanApplication.getRecordId() + " and are pleased to advise the sanction of credit facility as per following terms and conditions:\n\n";

        Paragraph paragraph3 = new Paragraph(line3, HELVETICA_SMALL);
        paragraph3.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph3);

        String[][] tableData = {
                {"Date of Application", date},
                {"Name of the Borrower (Borrower)", customer.getName()},
                {"Account type", loanType.getName()},
                {"Purpose", loanType.getName()},
                {"Loan Amount", String.valueOf(loanTemplate.getDesiredLoan())},
                {"Interest Type", "Fixed"},
                {"Rate of Interest", String.valueOf(loanTemplate.getInterestRate())},
                {"Tenure", String.valueOf(loanTemplate.getTenure())},
                {"Fees and Charges\n" +
                        "(Below charges are in INR and exclusive of GST).", ""},
                {"Platform processing fees", "5250"},
                {"Platform one time onboarding charges", "350"},
                {"Platform late payment charges", "Penalty charges applicable on repayment post due date for each instalment:\n" +
                        "First Overdue Day penalty charges 500 INR\n" +
                        "Penalty charges for 2-90 days 0.1 % of principal*\n" + "*round to nearest rupee"},
                {"Prepayment charges", "N/A"},
                {"Taxes & Levies", "All taxes including goods and services tax, duties and levies \n" +
                        "as per applicable law pertaining to the transaction (including on the charges mentioned above) +\n" +
                        "whether present or in future to be borne by the Borrower"},

        };

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new float[]{50f, 50f});

        Font normalFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);

        for (String[] row : tableData) {
            for (int i = 0; i < row.length; i++) {
                PdfPCell cell = new PdfPCell(new Phrase(row[i], normalFont));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setMinimumHeight(15f);
                table.addCell(cell);
            }
        }

        document.add(table);

        Paragraph paragraph5 = new Paragraph();
        leaveEmptyLine(paragraph5, 1);
        document.add(paragraph5);

        Font bulletFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.BLACK);
        com.itextpdf.text.List bulletList = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        bulletList.setIndentationLeft(5);
        bulletList.setListSymbol(new Chunk("\u2022 ", bulletFont));

        bulletList.add(new ListItem("ANY GRIEVANCE REGARDING ABOVE TERMS & CONDITIONS OR ANY GRIEVANCE REGARDING THE FACILITY," +
                "PLEASE CONTACT US AT 8044XXXXXX (MON-FRI 10:00 A.M. TO 9:00 P.M. AND SAT-10:00 A.M. TO 7:00 P.M.) OR" +
                " WRITE TO US AT REACHUS@XXXXXC.IN"));
        bulletList.add(new ListItem("Shree Meenakshi Finance Practices Code web link for Grievance Redressal Mechanism - https://www.shreeXXXXXX.in/fair-practice-code"));
        bulletList.add(new ListItem("All charges mentioned above will either be payable upfront or deducted from disbursal amount."));

        document.add(bulletList);

    }

    private void createLoanDetailsTable(Document document, String loanApplicationId) throws DocumentException {
        Paragraph paragraph = new Paragraph();
        leaveEmptyLine(paragraph, 1);
        paragraph.add(new Paragraph("Loan Details", HELVETICA));
        leaveEmptyLine(paragraph, 1);
        document.add(paragraph);

        List<String> loanTemplateColumnNames = new ArrayList<>();
        loanTemplateColumnNames.add("Loan Type");
        loanTemplateColumnNames.add("Loan Name");
        loanTemplateColumnNames.add("Interest Rate");
        loanTemplateColumnNames.add("Tenure");
        loanTemplateColumnNames.add("Desired Loan");

        PdfPTable table1 = new PdfPTable(loanTemplateColumnNames.size());

        for (int i = 0; i < loanTemplateColumnNames.size(); i++) {
            PdfPCell cell1 = new PdfPCell(new Phrase(loanTemplateColumnNames.get(i)));
            cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table1.addCell(cell1);
        }

        table1.setHeaderRows(1);
        getLoanTemplateData(table1, loanApplicationId);
        document.add(table1);
    }

    private void createLoanEmiDetailsTable(Document document, Loan loan) throws DocumentException {
        Paragraph paragraph = new Paragraph();
        leaveEmptyLine(paragraph, 1);
        document.add(paragraph);

        List<String> loanEmiDetailsColumnNames = new ArrayList<>();
        loanEmiDetailsColumnNames.add("S.No");
        loanEmiDetailsColumnNames.add("Principal (INR)");
        loanEmiDetailsColumnNames.add("Interest (INR)");
        loanEmiDetailsColumnNames.add("Fees (INR)");
        loanEmiDetailsColumnNames.add("Due Date");
        loanEmiDetailsColumnNames.add("Repayable Amount (INR)");

        PdfPTable table2 = new PdfPTable(loanEmiDetailsColumnNames.size());

        for (int i = 0; i < loanEmiDetailsColumnNames.size(); i++) {
            PdfPCell cell2 = new PdfPCell(new Phrase(loanEmiDetailsColumnNames.get(i)));
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell2);
        }

        table2.setHeaderRows(1);
        getLoanEmiDetailsData(table2, loan.getLoanEmiDetailDtoList());

        document.add(table2);
    }

    private void getLoanTemplateData(PdfPTable table, String loanApplicationId) {
        LoanApplication loanApplication = loanApplicationRepository.findByRecordId(loanApplicationId);

        LoanTemplate loanTemplate = loanTemplateRepository.findByRecordId(loanApplication.getLoanTemplateId());
        LoanType loanType = loanTypeRepository.findByRecordId(loanTemplate.getLoanType());

        table.setWidthPercentage(100);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

        table.addCell(loanType.getName());
        table.addCell(loanTemplate.getLoanName());
        table.addCell(String.valueOf(loanTemplate.getInterestRate()));
        table.addCell(String.valueOf(loanTemplate.getTenure()));
        table.addCell(String.valueOf(loanTemplate.getDesiredLoan()));

    }

    private void getLoanEmiDetailsData(PdfPTable table, List<LoanEmiDetailDto> loanEmiDetailDtoList) {

        table.setWidthPercentage(100);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

        for (int i = 0; i < loanEmiDetailDtoList.size(); i++) {
            table.addCell(String.valueOf(i + 1));
            table.addCell(String.valueOf(loanEmiDetailDtoList.get(i).getInstalment()));
            table.addCell(String.valueOf(loanEmiDetailDtoList.get(i).getInterestAmount()));
            table.addCell(String.valueOf(loanEmiDetailDtoList.get(i).getPenalty()));
            table.addCell(String.valueOf(loanEmiDetailDtoList.get(i).getDueDate()));
            table.addCell(String.valueOf(loanEmiDetailDtoList.get(i).getTotalPayable()));
        }
    }

    private void addTermsAndConditions(Document document) throws DocumentException {

        Paragraph paragraph = new Paragraph();
        leaveEmptyLine(paragraph, 1);
        paragraph.add(new Paragraph("Terms and Conditions:", HELVETICA_SMALL_BOLD));
        document.add(paragraph);
        paragraph.setAlignment(Element.ALIGN_LEFT);
        paragraph.add(new Paragraph("I/We acknowledge that:", HELVETICA_SMALL_BOLD));

        com.itextpdf.text.List bulletList = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        Font bulletFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK);
        bulletList.setIndentationLeft(5);
        bulletList.setListSymbol(new Chunk("\u2022 ", bulletFont));

        bulletList.add(new ListItem("These are the most important terms of the aforesaid Loan, and all other terms and conditions of the Loan shall be as" +
                " specified in the Application Form."));
//        bulletList.add(new ListItem("As may be applicable the Platform Processing Fees, Platform One Time Onboarding Fees, Platform Credit Reassessment" +
//                " Fees, Platform Late Payment Charges, Platform Document Collection Charges, Platform Agreement Fees, Prepayment" +
//                " Charges, Down payment and Platform Credit Report Charges along with applicable taxes shall be paid to and collected by" +
//                " the platform- XXXXXXXX Tech Solution Private Limited (GST NO- XXXXXXXXXX) (\"XXXXXXX\"), which is a distinct" +
//                " and separate entity from the Shree Meenakshi Finance Services private Limited (\"Lender\"). The Lender is not liable to collect any such " +
//                "fee & charges and to pay any applicable taxes on the same."));
//        bulletList.add(new ListItem("The above charges may be modified by Shree Meenakshi Finance without notice in case prescribed by any of the regulatory authorities and " +
//                "with due notice or intimation in any other scenarios through any of the communication process mentioned in the Application Form."));
        bulletList.add(new ListItem("Lender, at its sole discretion, shall be entitled to revoke this sanction upon occurrence of any of the following events:"));
        document.add(bulletList);
        com.itextpdf.text.List bulletList1 = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        bulletList1.setIndentationLeft(20);
        bulletList1.setListSymbol(new Chunk("\u2022 ", bulletFont));

        bulletList1.add(new ListItem("There is any material change in the purpose for which the Loan has been sanctioned."));
        bulletList1.add(new ListItem("In the sole judgment of Lender, any material facts have been concealed and / or become subsequently known."));
        bulletList1.add(new ListItem("Any statement, declaration, undertaking or disclosure made by, or on behalf of, the Borrower/Customer in the" +
                " application or otherwise is incorrect, inaccurate, incomplete or misleading."));
        bulletList1.add(new ListItem("There is a default or a breach of the terms and conditions of this Sanction Letter and the Application Form."));
        bulletList1.add(new ListItem("If there is any bankruptcy or insolvency proceeding filed or admitted against the Borrower/Customer."));
        bulletList1.add(new ListItem("Relevant documents are not executed by the Borrower as per Shree Meenakshi Finance's policy and format."));

        document.add(bulletList1);

        com.itextpdf.text.List bulletList2 = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        bulletList2.setIndentationLeft(5);
        bulletList2.setListSymbol(new Chunk("\u2022 ", bulletFont));

        bulletList2.add(new ListItem("I am aware that the Sanction Letter, Loan Application Form and other incidental documents executed by me integrate all" +
                " the conditions mentioned herein or incidental thereto, and supersede all negotiations or prior writings, except for those" +
                " provisions specified herein. In the event of any conflict between the terms, conditions and provisions of the Sanction" +
                " Letter/Loan Application Form/ documents executed incidental thereto with the terms mentioned herein, then in such an" +
                " event the terms, conditions and provisions mentioned herein shall prevail"));
        bulletList2.add(new ListItem("The sanction of the abovementioned Facility and all the terms and conditions mentioned in this Sanction Letter are subject" +
                " to the execution of a Loan Application Form and other documents in writing in physical or digital form (\"Loan Documents\")" +
                " as Shree Meenakshi Finance may specify in the prescribed formats. This Sanction Letter intends to summarize certain basic terms of the" +
                " Loan and the Loan Application Form and does not reflect the complete agreement between Shree Meenakshi Finance and the Borrower in" +
                " relation to the Loan"));
        bulletList2.add(new ListItem("The Loan Documents shall contain additional terms and conditions which have not been set out in this Sanction Letter and" +
                " the Loan Documents shall be read together with the terms and conditions specified in this Sanction Letter"));
        bulletList2.add(new ListItem("Notwithstanding the issuance of this Sanction Letter and the acceptance thereof, Shree Meenakshi Finance may decide to not disburse the" +
                " entire or part of the Loan, repudiate and rescind this Sanction Letter unilaterally without assigning any reasons"));
        bulletList2.add(new ListItem("Disclosure: As a precondition to the Facility to be granted to the Borrower by the Shree Meenakshi Finance, the Borrower by accepting this" +
                " Sanction Letter authorize, consent and agree for the disclosure and sharing by the Shree Meenakshi Finance of all or any information and" +
                " data relating to the Borrower to the Reserve Bank of India (\"RBI\") and/or to the Credit Information Bureau (India) Ltd" +
                " (\"CIBIL\") and/or to any other agency authorized in this behalf by RBI / CIBIL, to the Shree Meenakshi Finance's professional advisers and" +
                " consultants, to its affiliates/ subsidiaries, agents, and to its service providers. In case of default in the repayment of the loan/" +
                " advances/facility/interest on due dates, Shree Meenakshi Finance and/or the RBI / CIBIL will have an unqualified right to disclose or publish" +
                " the name of the Borrower and its directors / partners as defaulter in such manner and through such medium as Shree Meenakshi Finance or" +
                " the RBI in their absolute discretion may think fit"));
        bulletList2.add(new ListItem("In the event of any change of address for communication, any change in the job/ profession of the Borrower, the same needs" +
                " to be intimated by the Borrower to Shree Meenakshi Finance, within one month"));
        bulletList2.add(new ListItem("Confidentiality: The Sanction Letter and its content are intended for the exclusive use of the Borrower and shall not be" +
                " disclosed by the Borrower to any person other than the Borrower's legal advisors for the purposes of the proposed" +
                " transaction unless the prior written consent of the Lender is obtained"));
        bulletList2.add(new ListItem("Representations and Warranties: Usual and customary for transactions of this nature, including but not limited to" +
                " maintenance of existence; notices of default, material litigation; compliance with applicable laws and decrees; payment" +
                " of taxes; maintenance and insurance."));

        document.add(bulletList2);

    }

    private void addFooter(Document document) throws DocumentException {
        Paragraph p2 = new Paragraph();
        leaveEmptyLine(p2, 2);
        p2.setAlignment(Element.ALIGN_CENTER);
        p2.add(new Paragraph(
                "*** This is a System Generated Sanction letter and does Not Require any Signature***",
                HELVETICA_SMALL_FOOTER));

        document.add(p2);
    }

    private void addSignatureImage(Document document, String loanApplicationId) {

        Paragraph paragraph = new Paragraph();
        leaveEmptyLine(paragraph, 2);
        Float[] logoImgScale = {7.5F, 7.5F};

        LoanApplication loanApplication = loanApplicationRepository.findByRecordId(loanApplicationId);
        Customer customer = customerRepository.findByRecordId(loanApplication.getCustomerId());

        String customerDetails = "Name:  " + customer.getName() + "\n" +
                "\n" +
                "Mobile Number: " + customer.getPhone() + "\n" +
                "\n" +
                "Address: " + customer.getAddress() + "\n" +
                "\n";
        String base64Image = loanApplication.getImages();
        try {

            if (base64Image.contains(",")) {
                base64Image = base64Image.split(",")[1];
            }

            byte[] imageBytes = Base64.getDecoder().decode(base64Image);
            Image img = Image.getInstance(imageBytes);
            img.scalePercent(logoImgScale[0], logoImgScale[1]);
            img.setAlignment(Element.ALIGN_RIGHT);

            PdfPTable table = new PdfPTable(2);
            table.setWidthPercentage(100);
            table.setWidths(new float[]{50f, 50f});

            PdfPCell titleCell = new PdfPCell(new Phrase(customerDetails, HELVETICA_SMALL));
            titleCell.setBorder(Rectangle.NO_BORDER);
            titleCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            titleCell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(titleCell);

            PdfPCell imageCell = new PdfPCell(img, false);
            imageCell.setBorder(Rectangle.NO_BORDER);
            imageCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            imageCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(imageCell);

            document.add(paragraph);
            document.add(table);

        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }

    private void addSignature(Document document) throws DocumentException {

        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100);

        PdfPCell signatureCell = new PdfPCell(new Phrase(signature, HELVETICA));
        signatureCell.setBorder(Rectangle.NO_BORDER);
        signatureCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        signatureCell.setVerticalAlignment(Element.ALIGN_MIDDLE);

        table.addCell(signatureCell);
        document.add(table);

    }

}


//        public void generatePdfReport(String loanTemplateId) {
//
//            Document document = new Document();
//
//            try {
//                PdfWriter.getInstance(document, new FileOutputStream(getPdfNameWithDate()));
//                document.open();
//                addTitleAndLogo(document);
//                //addDocTitle(document);
//                createLoanDetailsTable(document, loanTemplateId);
//                createLoanEmiDetailsTable(document, loanTemplateId);
//                addFooter(document);
//                document.close();
//
//            } catch (FileNotFoundException | DocumentException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//
//        }


//        private void addDocTitle(Document document) throws DocumentException {
//            String localDateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern(localDateFormat));
//            Paragraph p1 = new Paragraph();
//            //leaveEmptyLine(p1, 1);
//            p1.add(new Paragraph(reportFileName, HELVETICA));
//            p1.setAlignment(Element.ALIGN_CENTER);
//            leaveEmptyLine(p1, 1);
//            p1.add(new Paragraph("Report generated on " + localDateString, HELVETICA_SMALL));
//            document.add(p1);
//
//        }


//        private String getPdfNameWithDate() {
/// /            String localDateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern(reportFileNameDateFormat));
/// /            return pdfDir+reportFileName+"-"+localDateString+".pdf";
//            SimpleDateFormat sdf = new SimpleDateFormat(reportFileNameDateFormat);
//            String datePart = sdf.format(new Date());
//
//            SimpleDateFormat sdfTime = new SimpleDateFormat("HHmmss");
//            String timePart = sdfTime.format(new Date());
//
//            return pdfDir + reportFileName + "_" + datePart + "_" + timePart + ".pdf";
//        }