package com.reallinkbilling.download;

import static java.awt.Color.WHITE;
import static org.apache.pdfbox.pdmodel.font.PDType1Font.HELVETICA;
import static org.vandeseer.easytable.settings.HorizontalAlignment.CENTER;
import static org.vandeseer.easytable.settings.HorizontalAlignment.LEFT;
import static org.vandeseer.easytable.settings.HorizontalAlignment.RIGHT;

import java.awt.Color;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import org.vandeseer.easytable.TableDrawer;
import org.vandeseer.easytable.structure.Row;
import org.vandeseer.easytable.structure.Table;
import org.vandeseer.easytable.structure.Table.TableBuilder;
import org.vandeseer.easytable.structure.cell.TextCell;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.db.GetDBConnection;

public class DownloadpurchaseList extends ActionSupport implements SessionAware {

    private static final long serialVersionUID = 1L;

    private HttpSession session;

    private HttpServletRequest request;
    private HttpServletResponse response;

    private SessionMap<String, Object> sessionMap;

    private String fromDate;
    private String toDate;
    private String supplierName;

    private double totalBillingAmount;
    private double totalPaidAmount;
    private double totalCreditAmount;

    private static final float PADDING5 = 5f;
    private static final float PADDING20 = 20f;
    private static final float PADDING30 = 30f;

    public void download() {

        this.setSession(
                ServletActionContext.getRequest().getSession(false)
        );

        if (this.getSession() == null
                || this.getSession().getAttribute("login") == null) {

            addActionMessage("Please Login First !!!");
            return;
        }

        response = ServletActionContext.getResponse();
        request = ServletActionContext.getRequest();

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        String shopId = (String) this.getSessionMap().get("shopId");
        String shopCode = (String) this.getSessionMap().get("shopCode");
        String db = (String) this.getSessionMap().get("db");

        String shopName = (String) this.getSessionMap()
                .get("shopnameenglish");

        /*
         * Reset totals
         */
        totalBillingAmount = 0.0;
        totalPaidAmount = 0.0;
        totalCreditAmount = 0.0;

        try {

            connection = GetDBConnection.getDBConnection(db);

            String sql;

            /*
             * Purchase report without supplier filter
             */
            if (supplierName == null || supplierName.trim().equals("")) {

                sql = "SELECT "
                        + "purchase_number,"
                        + "purchase_invoice_number,"
                        + "DATE_FORMAT(purchase_date,'%d-%m-%Y'),"
                        + "purchase_time,"
                        + "payment_type,"
                        + "supplier_id,"
                        + "supplier_name,"
                        + "transportation_charges,"
                        + "other_expenses,"
                        + "comments,"
                        + "total_purchase_amount,"
                        + "purchase_amount_paid,"
                        + "purchase_cgst_amount,"
                        + "purchase_scgst_amount,"
                        + "purchase_igst_amount,"
                        + "purchase_net_amount,"
                        + "entry_by,"
                        + "invoice_pic,"
                        + "purchased_by "
                        + "FROM shop_purchase_info_master "
                        + "WHERE shop_id = ? "
                        + "AND shop_code = ? "
                        + "AND purchase_date BETWEEN "
                        + "STR_TO_DATE(?,'%d-%m-%Y') "
                        + "AND STR_TO_DATE(?,'%d-%m-%Y') "
                        + "ORDER BY purchase_date, purchase_time";

                preparedStatement = connection.prepareStatement(sql);

                preparedStatement.setString(1, shopId);
                preparedStatement.setString(2, shopCode);
                preparedStatement.setString(3, this.getFromDate());
                preparedStatement.setString(4, this.getToDate());

            } else {

                /*
                 * Purchase report with supplier filter
                 */
                sql = "SELECT "
                        + "purchase_number,"
                        + "purchase_invoice_number,"
                        + "DATE_FORMAT(purchase_date,'%d-%m-%Y'),"
                        + "purchase_time,"
                        + "payment_type,"
                        + "supplier_id,"
                        + "supplier_name,"
                        + "transportation_charges,"
                        + "other_expenses,"
                        + "comments,"
                        + "total_purchase_amount,"
                        + "purchase_amount_paid,"
                        + "purchase_cgst_amount,"
                        + "purchase_scgst_amount,"
                        + "purchase_igst_amount,"
                        + "purchase_net_amount,"
                        + "entry_by,"
                        + "invoice_pic,"
                        + "purchased_by "
                        + "FROM shop_purchase_info_master "
                        + "WHERE supplier_name LIKE ? "
                        + "AND shop_id = ? "
                        + "AND shop_code = ? "
                        + "AND purchase_date BETWEEN "
                        + "STR_TO_DATE(?,'%d-%m-%Y') "
                        + "AND STR_TO_DATE(?,'%d-%m-%Y') "
                        + "ORDER BY purchase_date, purchase_time";

                preparedStatement = connection.prepareStatement(sql);

                preparedStatement.setString(
                        1,
                        "%" + this.getSupplierName().trim() + "%"
                );

                preparedStatement.setString(2, shopId);
                preparedStatement.setString(3, shopCode);
                preparedStatement.setString(4, this.getFromDate());
                preparedStatement.setString(5, this.getToDate());
            }

            resultSet = preparedStatement.executeQuery();

            /*
             * Create PDF
             */
            String path = request.getSession()
                    .getServletContext()
                    .getRealPath("/images/");

            String fileName =
                    "purchase-dateWise-fromDate-"
                    + this.getFromDate()
                    + "-ToDate-"
                    + this.getToDate()
                    + "-report.pdf";

            String filePath = path + "/" + fileName;

            PDDocument document = new PDDocument();

            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            PDPageContentStream contentStream =
                    new PDPageContentStream(document, page);

            int pageCount = 1;

            /*
             * ============================
             * HEADER TABLE
             * ============================
             */

            TableBuilder tableHeaderBuilder = Table.builder()
                    .addColumnsOfWidth(545)
                    .font(HELVETICA)
                    .borderColor(Color.BLACK)
                    .horizontalAlignment(CENTER);

            Row headerName = Row.builder()
                    .add(
                            TextCell.builder()
                                    .text(
                                            shopName == null
                                                    ? ""
                                                    : shopName
                                    )
                                    .horizontalAlignment(CENTER)
                                    .borderWidth(0)
                                    .lineSpacing(10F)
                                    .build()
                    )
                    .backgroundColor(WHITE)
                    .textColor(Color.BLACK)
                    .font(PDType1Font.HELVETICA_BOLD)
                    .fontSize(18)
                    .horizontalAlignment(CENTER)
                    .build();

            Row reportName = Row.builder()
                    .add(
                            TextCell.builder()
                                    .text(
                                            "Purchase Report DateWise"
                                            + "       Page No. : "
                                            + pageCount
                                    )
                                    .borderWidthBottom(0.0F)
                                    .horizontalAlignment(CENTER)
                                    .build()
                    )
                    .backgroundColor(WHITE)
                    .textColor(Color.BLACK)
                    .font(PDType1Font.HELVETICA_BOLD)
                    .fontSize(11)
                    .horizontalAlignment(CENTER)
                    .build();

            String supplierFilterText = "";

            if (supplierName != null
                    && !supplierName.trim().equals("")) {

                supplierFilterText =
                        " and Supplier : "
                        + supplierName.trim();
            }

            Row dateInfo = Row.builder()
                    .add(
                            TextCell.builder()
                                    .text(
                                            "From Date : "
                                            + this.getFromDate()
                                            + " and To Date : "
                                            + this.getToDate()
                                            + supplierFilterText
                                    )
                                    .borderWidthBottom(0.0F)
                                    .horizontalAlignment(CENTER)
                                    .build()
                    )
                    .backgroundColor(WHITE)
                    .textColor(Color.BLACK)
                    .font(PDType1Font.HELVETICA_BOLD)
                    .fontSize(8)
                    .horizontalAlignment(CENTER)
                    .build();

            tableHeaderBuilder.addRow(headerName);
            tableHeaderBuilder.addRow(reportName);
            tableHeaderBuilder.addRow(dateInfo);

            Table header = tableHeaderBuilder.build();

            /*
             * ============================
             * PURCHASE DETAILS TABLE
             * ============================
             *
             * Columns:
             *
             * 1. Purchase Date
             * 2. Invoice Number
             * 3. Supplier Name
             * 4. Billing Amount
             * 5. Paid Amount
             * 6. Credit Amount
             * 7. Purchase By
             * 8. Entry By
             */

            TableBuilder purchaseDetailsBuilder = Table.builder()
                    .addColumnsOfWidth(
                            65,
                            70,
                            140,
                            75,
                            70,
                            70,
                            55,
                            40
                    )
                    .font(HELVETICA)
                    .borderWidth(0.5F)
                    .borderColor(Color.BLACK)
                    .horizontalAlignment(CENTER);

            Row tableHeader = Row.builder()

                    .add(
                            TextCell.builder()
                                    .text("Purchase Date")
                                    .horizontalAlignment(LEFT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("Invoice Number")
                                    .horizontalAlignment(LEFT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("Supplier Name")
                                    .horizontalAlignment(LEFT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("Billing Amount")
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("Paid Amount")
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("Credit Amount")
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("Purchase By")
                                    .horizontalAlignment(LEFT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("Entry By")
                                    .horizontalAlignment(LEFT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .backgroundColor(Color.LIGHT_GRAY)
                    .textColor(Color.BLACK)
                    .font(PDType1Font.HELVETICA_BOLD)
                    .fontSize(8)
                    .horizontalAlignment(CENTER)
                    .build();

            purchaseDetailsBuilder.addRow(tableHeader);

            /*
             * Draw header
             */
            float startY =
                    page.getMediaBox().getHeight() - PADDING20;

            float currentY = startY;

            TableDrawer.builder()
                    .contentStream(contentStream)
                    .table(header)
                    .startX(PADDING30)
                    .startY(startY)
                    .build()
                    .draw();

            /*
             * Header takes approximately 70 pixels
             */
            currentY = startY - 70;

            boolean recordFound = false;

            /*
             * ============================
             * READ PURCHASE RECORDS
             * ============================
             */

            while (resultSet.next()) {

                recordFound = true;

                String purchaseDate =
                        resultSet.getString(3);

                String invoiceNumber =
                        resultSet.getString(2);

                String supplier =
                        resultSet.getString(7);

                String billingAmountString =
                        resultSet.getString(11);

                String paidAmountString =
                        resultSet.getString(12);

                String purchaseBy =
                        resultSet.getString(19);

                String entryBy =
                        resultSet.getString(17);

                /*
                 * Convert Billing Amount
                 */
                double billingAmount = 0.0;

                try {

                    if (billingAmountString != null
                            && !billingAmountString.trim().equals("")) {

                        billingAmount =
                                Double.parseDouble(
                                        billingAmountString
                                );
                    }

                } catch (Exception e) {
                    billingAmount = 0.0;
                }

                /*
                 * Convert Paid Amount
                 */
                double paidAmount = 0.0;

                try {

                    if (paidAmountString != null
                            && !paidAmountString.trim().equals("")) {

                        paidAmount =
                                Double.parseDouble(
                                        paidAmountString
                                );
                    }

                } catch (Exception e) {
                    paidAmount = 0.0;
                }

                /*
                 * Credit Amount
                 *
                 * Credit = Billing - Paid
                 *
                 * If negative, show 0
                 */
                double creditAmount =
                        billingAmount - paidAmount;

                if (creditAmount < 0) {
                    creditAmount = 0.0;
                }

                /*
                 * Add to totals
                 */
                totalBillingAmount += billingAmount;
                totalPaidAmount += paidAmount;
                totalCreditAmount += creditAmount;

                /*
                 * Check page space
                 */
                if (currentY < 100) {

                    /*
                     * Draw current table before
                     * creating a new page.
                     */
                    Table purchaseDetails =
                            purchaseDetailsBuilder.build();

                    TableDrawer.builder()
                            .contentStream(contentStream)
                            .table(purchaseDetails)
                            .startX(PADDING5)
                            .startY(startY - 75)
                            .build()
                            .draw();

                    contentStream.close();

                    /*
                     * New page
                     */
                    pageCount++;

                    page = new PDPage(PDRectangle.A4);

                    document.addPage(page);

                    contentStream =
                            new PDPageContentStream(
                                    document,
                                    page
                            );

                    /*
                     * Create new header
                     */
                    tableHeaderBuilder =
                            Table.builder()
                                    .addColumnsOfWidth(545)
                                    .font(HELVETICA)
                                    .borderColor(Color.BLACK)
                                    .horizontalAlignment(CENTER);

                    headerName = Row.builder()
                            .add(
                                    TextCell.builder()
                                            .text(
                                                    shopName == null
                                                            ? ""
                                                            : shopName
                                            )
                                            .horizontalAlignment(CENTER)
                                            .borderWidth(0)
                                            .lineSpacing(10F)
                                            .build()
                            )
                            .backgroundColor(WHITE)
                            .textColor(Color.BLACK)
                            .font(
                                    PDType1Font.HELVETICA_BOLD
                            )
                            .fontSize(18)
                            .horizontalAlignment(CENTER)
                            .build();

                    reportName = Row.builder()
                            .add(
                                    TextCell.builder()
                                            .text(
                                                    "Purchase Report DateWise"
                                                    + "       Page No. : "
                                                    + pageCount
                                            )
                                            .borderWidthBottom(0.0F)
                                            .horizontalAlignment(CENTER)
                                            .build()
                            )
                            .backgroundColor(WHITE)
                            .textColor(Color.BLACK)
                            .font(
                                    PDType1Font.HELVETICA_BOLD
                            )
                            .fontSize(11)
                            .horizontalAlignment(CENTER)
                            .build();

                    dateInfo = Row.builder()
                            .add(
                                    TextCell.builder()
                                            .text(
                                                    "From Date : "
                                                    + this.getFromDate()
                                                    + " and To Date : "
                                                    + this.getToDate()
                                                    + supplierFilterText
                                            )
                                            .borderWidthBottom(0.0F)
                                            .horizontalAlignment(CENTER)
                                            .build()
                            )
                            .backgroundColor(WHITE)
                            .textColor(Color.BLACK)
                            .font(
                                    PDType1Font.HELVETICA_BOLD
                            )
                            .fontSize(8)
                            .horizontalAlignment(CENTER)
                            .build();

                    tableHeaderBuilder.addRow(headerName);
                    tableHeaderBuilder.addRow(reportName);
                    tableHeaderBuilder.addRow(dateInfo);

                    header = tableHeaderBuilder.build();

                    /*
                     * Create new purchase table
                     */
                    purchaseDetailsBuilder =
                            Table.builder()
                                    .addColumnsOfWidth(
                                            65,
                                            70,
                                            140,
                                            75,
                                            70,
                                            70,
                                            55,
                                            40
                                    )
                                    .font(HELVETICA)
                                    .borderWidth(0.5F)
                                    .borderColor(Color.BLACK)
                                    .horizontalAlignment(CENTER);

                    tableHeader = Row.builder()

                            .add(
                                    TextCell.builder()
                                            .text("Purchase Date")
                                            .horizontalAlignment(LEFT)
                                            .borderWidth(0.5F)
                                            .lineSpacing(1F)
                                            .build()
                            )

                            .add(
                                    TextCell.builder()
                                            .text("Invoice Number")
                                            .horizontalAlignment(LEFT)
                                            .borderWidth(0.5F)
                                            .lineSpacing(1F)
                                            .build()
                            )

                            .add(
                                    TextCell.builder()
                                            .text("Supplier Name")
                                            .horizontalAlignment(LEFT)
                                            .borderWidth(0.5F)
                                            .lineSpacing(1F)
                                            .build()
                            )

                            .add(
                                    TextCell.builder()
                                            .text("Billing Amount")
                                            .horizontalAlignment(RIGHT)
                                            .borderWidth(0.5F)
                                            .lineSpacing(1F)
                                            .build()
                            )

                            .add(
                                    TextCell.builder()
                                            .text("Paid Amount")
                                            .horizontalAlignment(RIGHT)
                                            .borderWidth(0.5F)
                                            .lineSpacing(1F)
                                            .build()
                            )

                            .add(
                                    TextCell.builder()
                                            .text("Credit Amount")
                                            .horizontalAlignment(RIGHT)
                                            .borderWidth(0.5F)
                                            .lineSpacing(1F)
                                            .build()
                            )

                            .add(
                                    TextCell.builder()
                                            .text("Purchase By")
                                            .horizontalAlignment(LEFT)
                                            .borderWidth(0.5F)
                                            .lineSpacing(1F)
                                            .build()
                            )

                            .add(
                                    TextCell.builder()
                                            .text("Entry By")
                                            .horizontalAlignment(LEFT)
                                            .borderWidth(0.5F)
                                            .lineSpacing(1F)
                                            .build()
                            )

                            .backgroundColor(Color.LIGHT_GRAY)
                            .textColor(Color.BLACK)
                            .font(
                                    PDType1Font.HELVETICA_BOLD
                            )
                            .fontSize(8)
                            .horizontalAlignment(CENTER)
                            .build();

                    purchaseDetailsBuilder.addRow(tableHeader);

                    /*
                     * Draw new page header
                     */
                    startY =
                            page.getMediaBox().getHeight()
                            - PADDING20;

                    currentY = startY;

                    TableDrawer.builder()
                            .contentStream(contentStream)
                            .table(header)
                            .startX(PADDING30)
                            .startY(startY)
                            .build()
                            .draw();

                    currentY = startY - 70;
                }

                /*
                 * ============================
                 * PURCHASE ROW
                 * ============================
                 */

                Row purchaseInfo = Row.builder()

                        .add(
                                TextCell.builder()
                                        .text(
                                                purchaseDate == null
                                                        ? ""
                                                        : purchaseDate
                                        )
                                        .horizontalAlignment(LEFT)
                                        .borderWidth(0.5F)
                                        .lineSpacing(1F)
                                        .build()
                        )

                        .add(
                                TextCell.builder()
                                        .text(
                                                invoiceNumber == null
                                                        ? ""
                                                        : invoiceNumber
                                        )
                                        .horizontalAlignment(LEFT)
                                        .borderWidth(0.5F)
                                        .lineSpacing(1F)
                                        .build()
                        )

                        .add(
                                TextCell.builder()
                                        .text(
                                                supplier == null
                                                        ? ""
                                                        : supplier
                                        )
                                        .horizontalAlignment(LEFT)
                                        .borderWidth(0.5F)
                                        .lineSpacing(1F)
                                        .build()
                        )

                        .add(
                                TextCell.builder()
                                        .text(
                                                String.format(
                                                        "%.2f",
                                                        billingAmount
                                                )
                                        )
                                        .horizontalAlignment(RIGHT)
                                        .borderWidth(0.5F)
                                        .lineSpacing(1F)
                                        .build()
                        )

                        .add(
                                TextCell.builder()
                                        .text(
                                                String.format(
                                                        "%.2f",
                                                        paidAmount
                                                )
                                        )
                                        .horizontalAlignment(RIGHT)
                                        .borderWidth(0.5F)
                                        .lineSpacing(1F)
                                        .build()
                        )

                        .add(
                                TextCell.builder()
                                        .text(
                                                String.format(
                                                        "%.2f",
                                                        creditAmount
                                                )
                                        )
                                        .horizontalAlignment(RIGHT)
                                        .borderWidth(0.5F)
                                        .lineSpacing(1F)
                                        .build()
                        )

                        .add(
                                TextCell.builder()
                                        .text(
                                                purchaseBy == null
                                                        ? ""
                                                        : purchaseBy
                                        )
                                        .horizontalAlignment(LEFT)
                                        .borderWidth(0.5F)
                                        .lineSpacing(1F)
                                        .build()
                        )

                        .add(
                                TextCell.builder()
                                        .text(
                                                entryBy == null
                                                        ? ""
                                                        : entryBy
                                        )
                                        .horizontalAlignment(LEFT)
                                        .borderWidth(0.5F)
                                        .lineSpacing(1F)
                                        .build()
                        )

                        .backgroundColor(Color.WHITE)
                        .textColor(Color.BLACK)
                        .font(PDType1Font.HELVETICA)
                        .fontSize(8)
                        .horizontalAlignment(CENTER)
                        .height(25F)
                        .build();

                purchaseDetailsBuilder.addRow(purchaseInfo);

                currentY = currentY - 25;
            }

            /*
             * If no records found
             */
            if (!recordFound) {

                contentStream.close();
                document.close();

                addActionError(
                        "Details not found for information provided!"
                );

                return;
            }

            /*
             * ============================
             * TOTAL ROW
             * ============================
             */

            Row totalRow = Row.builder()

                    .add(
                            TextCell.builder()
                                    .text("TOTAL")
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("")
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("")
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text(
                                            String.format(
                                                    "%.2f",
                                                    totalBillingAmount
                                            )
                                    )
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text(
                                            String.format(
                                                    "%.2f",
                                                    totalPaidAmount
                                            )
                                    )
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text(
                                            String.format(
                                                    "%.2f",
                                                    totalCreditAmount
                                            )
                                    )
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("")
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .add(
                            TextCell.builder()
                                    .text("")
                                    .horizontalAlignment(RIGHT)
                                    .borderWidth(0.5F)
                                    .lineSpacing(1F)
                                    .build()
                    )

                    .backgroundColor(Color.WHITE)
                    .textColor(Color.BLACK)
                    .font(PDType1Font.HELVETICA_BOLD)
                    .fontSize(9)
                    .horizontalAlignment(CENTER)
                    .height(25F)
                    .build();

            purchaseDetailsBuilder.addRow(totalRow);

            /*
             * Build final table
             */
            Table purchaseDetails =
                    purchaseDetailsBuilder.build();

            /*
             * Draw final table
             */
            TableDrawer.builder()
                    .contentStream(contentStream)
                    .table(purchaseDetails)
                    .startX(PADDING5)
                    .startY(startY - 75)
                    .build()
                    .draw();

            /*
             * Close PDF stream
             */
            contentStream.close();

            /*
             * Save PDF
             */
            document.save(filePath);
            document.close();

            /*
             * Send PDF to browser
             */
            response.setContentType("application/pdf");

            response.setHeader(
                    "Content-Disposition",
                    "inline; filename=" + fileName
            );

            /*
             * Write file to response
             */
            FileInputStream fileInputStream =
                    new FileInputStream(filePath);

            OutputStream outputStream =
                    response.getOutputStream();

            byte[] buffer = new byte[8192];

            int bytesRead;

            while ((bytesRead =
                    fileInputStream.read(buffer)) != -1) {

                outputStream.write(
                        buffer,
                        0,
                        bytesRead
                );
            }

            outputStream.flush();

            fileInputStream.close();
            outputStream.close();

        } catch (SQLException e) {

            addActionError(
                    e.getErrorCode()
                    + " || "
                    + e.getMessage()
                    + " || Something Went Wrong!"
            );

        } catch (IOException e) {

            addActionError(
                    e.getMessage()
                    + " || "
                    + e.getCause()
                    + " || Something Went Wrong!"
            );

        } catch (Exception e) {

            addActionError(
                    e.getMessage()
                    + " || "
                    + e.getCause()
                    + " || Something Went Wrong!"
            );

        } finally {

            if (resultSet != null) {

                try {
                    resultSet.close();
                } catch (SQLException e) {
                }
            }

            if (preparedStatement != null) {

                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                }
            }

            if (connection != null) {

                try {
                    connection.close();
                } catch (SQLException e) {
                }
            }
        }
    }

    public HttpSession getSession() {
        return session;
    }

    public void setSession(HttpSession session) {
        this.session = session;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public SessionMap<String, Object> getSessionMap() {
        return sessionMap;
    }

    public void setSessionMap(
            SessionMap<String, Object> sessionMap) {

        this.sessionMap = sessionMap;
    }

    @Override
    public void setSession(Map<String, Object> map) {
        sessionMap =
                (SessionMap<String, Object>) map;
    }

    public String getFromDate() {
        return fromDate;
    }

    public void setFromDate(String fromDate) {
        this.fromDate = fromDate;
    }

    public String getToDate() {
        return toDate;
    }

    public void setToDate(String toDate) {
        this.toDate = toDate;
    }

    public String getSupplierName() {
        return supplierName;
    }

    public void setSupplierName(String supplierName) {
        this.supplierName = supplierName;
    }

    public double getTotalBillingAmount() {
        return totalBillingAmount;
    }

    public void setTotalBillingAmount(
            double totalBillingAmount) {

        this.totalBillingAmount =
                totalBillingAmount;
    }

    public double getTotalPaidAmount() {
        return totalPaidAmount;
    }

    public void setTotalPaidAmount(
            double totalPaidAmount) {

        this.totalPaidAmount =
                totalPaidAmount;
    }

    public double getTotalCreditAmount() {
        return totalCreditAmount;
    }

    public void setTotalCreditAmount(
            double totalCreditAmount) {

        this.totalCreditAmount =
                totalCreditAmount;
    }
}