/*
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
package com.arrebol.taxiservicios.beans.admin;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.Body;
import com.amazonaws.services.simpleemail.model.Content;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.Message;
import com.amazonaws.services.simpleemail.model.SendEmailRequest;
import com.amazonaws.services.simpleemail.model.SendEmailResult;
import com.arrebol.taxiservicios.beans.Datatable;
import com.arrebol.taxiservicios.beans.SendMSN;
import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.BitacoraController;
import com.arrebol.taxiservicios.controller.admin.ExpenseCompanyController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.admin.StableGeneralBoxController;
import com.arrebol.taxiservicios.model.admin.ClosingDay;
import com.arrebol.taxiservicios.model.admin.EmployeeSanction;
import com.arrebol.taxiservicios.model.admin.Expense;
import com.arrebol.taxiservicios.model.admin.ExpenseCompany;
import com.arrebol.taxiservicios.model.admin.Sale;
import com.arrebol.taxiservicios.model.admin.Sanction;
import com.arrebol.taxiservicios.model.admin.StableGeneralBox;
import com.arrebol.taxiservicios.model.admin.Taxes;
import com.arrebol.taxiservicios.model.admin.TransferMoneyLocation;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.ExpenseCompanyType;
import com.arrebol.taxiservicios.model.payroll.Adelantos;
import com.arrebol.taxiservicios.model.payroll.Payroll;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Font;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@Named("stableGeneralBoxBean")
@ViewScoped
public class StableGeneralBoxBean extends TaxiGenericBean implements Serializable, Datatable {

    public void imprimir() {
        Document document = new Document(PageSize.LETTER);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            PdfWriter.getInstance(document, baos);

            List<ClosingDay> resultsClosing = new ArrayList<>();
            List<ExpenseCompany> resultsExpenseIn = new ArrayList<>();
            List<ExpenseCompany> resultsExpenseOut = new ArrayList<>();
            List<ExpenseCompany> resultsExpenseAll = new ArrayList<>();
            List<Payroll> resultsPayroll = new ArrayList<>();
            List<Taxes> resultsTaxes = new ArrayList<>();
            List<Expense> resultsInicios = new ArrayList<>();
            List<TransferMoneyLocation> resultsTransfer = new ArrayList<>();
            List<Adelantos> resultsAdelantos = new ArrayList<>();
            List<EmployeeSanction> resultsSanction = new ArrayList<>();
            List<Sale> saleDeposit = new ArrayList<>();
            List<Sanction> sanctionDeposit = new ArrayList<>();

            double totalCortes = 0D;
            double totalExpenseIn = 0D;
            double totalExpenseOut = 0D;
            double totalPayroll = 0D;
            double totalTaxes = 0D;
            double totalInicios = 0D;
            double totalTransferSend = 0D;
            double totalTransferReceiver = 0D;
            double totalAdelantos = 0D;
            double totalSanction = 0D;

            BigDecimal lastStable = BigDecimal.ZERO;

            resultsClosing = getController().findClosingDailyListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            resultsExpenseIn = getController().findExpenseCompanyInListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            resultsExpenseOut = getController().findExpenseCompanyOutListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            resultsExpenseAll = getController().findExpenseCompanyAllListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            resultsPayroll = getController().findPayrollListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            resultsTaxes = getController().findTaxesListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            resultsInicios = getController().findIniciosListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            resultsTransfer = getController().findTransferListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            resultsAdelantos = getController().findAdelantosListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            resultsSanction = getController().findEmployeeSanctionListByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());
            saleDeposit = getController().findSaleDepositByStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());

            lastStable = getController().getLastStableGeneralBox(selectedRow.getCreatedOn(), getLoggedUser().getLocation().getId());

            User userTmp = selectedRow.getCreatedBy();
            document.open();

            DateFormat formatter = new SimpleDateFormat("dd/MM/yy");

            Paragraph printDate = new Paragraph("Fecha de impresión: " + formatter.format(new Date()), FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.DARK_GRAY));
            printDate.setAlignment(Element.ALIGN_RIGHT);
            document.add(printDate);

            Paragraph title = new Paragraph("Cuadre de caja general - " + selectedRow.getLocation().getName(), FontFactory.getFont("arial", 18, Font.BOLD, BaseColor.DARK_GRAY));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);

            document.add(Chunk.NEWLINE);

            PdfPTable table = new PdfPTable(7);
            table.setTotalWidth(new float[]{100, 60, 60, 60, 80, 100, 100});

            table.setLockedWidth(true);
            PdfPCell cell = new PdfPCell(new Paragraph("Cortes del dia",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setColspan(7);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("Usuario",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("Monto a reportar",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("Monto reportado",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("Diferencia",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("Fecha",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("Comentarios",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("Creado por",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

            if (resultsClosing != null && !resultsClosing.isEmpty()) {
                for (ClosingDay tmp : resultsClosing) {
                    totalCortes = totalCortes + tmp.getAmountExpected().doubleValue();
                    cell = new PdfPCell(new Paragraph(tmp.getUser().getPerson().getFirstName() + " " +tmp.getUser().getPerson().getSecondName() + " "+ tmp.getUser().getPerson().getLastName()+ " " + tmp.getUser().getPerson().getMiddleName(), 
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setColspan(1);
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph(tmp.getAmountExpected().doubleValue() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setColspan(1);
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph(tmp.getAmountPaid().doubleValue() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setColspan(1);
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph((tmp.getAmountPaid().subtract(tmp.getAmountExpected())).doubleValue() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setColspan(1);
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph(tmp.getCreatedOn().toString(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setColspan(1);
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph(tmp.getComments(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setColspan(1);
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph(tmp.getCreatedBy().getPerson().getFirstName() + " " + tmp.getCreatedBy().getPerson().getSecondName() +" "+ tmp.getCreatedBy().getPerson().getLastName() + " " + tmp.getCreatedBy().getPerson().getMiddleName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setColspan(1);
                    table.addCell(cell);
                }
                document.add(table);

                document.add(Chunk.createWhitespace(""));
            }

            PdfPTable tableExpenseIn = new PdfPTable(4);
            tableExpenseIn.setTotalWidth(new float[]{100, 100, 100, 100});

            tableExpenseIn.setLockedWidth(true);
            PdfPCell cellExpenseIn = new PdfPCell(new Paragraph("Entradas/Gastos administrativos",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellExpenseIn.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellExpenseIn.setBackgroundColor(BaseColor.BLUE);
            cellExpenseIn.setColspan(4);
            tableExpenseIn.addCell(cellExpenseIn);

            cellExpenseIn = new PdfPCell(new Paragraph("Monto",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellExpenseIn.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellExpenseIn.setColspan(1);
            tableExpenseIn.addCell(cellExpenseIn);

            cellExpenseIn = new PdfPCell(new Paragraph("Tipo",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellExpenseIn.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellExpenseIn.setColspan(1);
            tableExpenseIn.addCell(cellExpenseIn);

            cellExpenseIn = new PdfPCell(new Paragraph("Descripción",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellExpenseIn.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellExpenseIn.setColspan(1);
            tableExpenseIn.addCell(cellExpenseIn);

            cellExpenseIn = new PdfPCell(new Paragraph("Usuario",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellExpenseIn.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellExpenseIn.setColspan(1);
            tableExpenseIn.addCell(cellExpenseIn);

            if (resultsExpenseAll != null && !resultsExpenseAll.isEmpty()) {
                for (ExpenseCompany tmp : resultsExpenseAll) {
                    cellExpenseIn = new PdfPCell(new Paragraph(tmp.getAmount().doubleValue() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellExpenseIn.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellExpenseIn.setColspan(1);
                    tableExpenseIn.addCell(cellExpenseIn);

                    cellExpenseIn = new PdfPCell(new Paragraph(tmp.getExpenseCompanyType().getLabel(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellExpenseIn.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellExpenseIn.setColspan(1);
                    tableExpenseIn.addCell(cellExpenseIn);

                    cellExpenseIn = new PdfPCell(new Paragraph(tmp.getDescription(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellExpenseIn.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellExpenseIn.setColspan(1);
                    tableExpenseIn.addCell(cellExpenseIn);

                    cellExpenseIn = new PdfPCell(new Paragraph(tmp.getCreatedBy().getPerson().getFirstName() + " " + tmp.getCreatedBy().getPerson().getSecondName() +" "+ tmp.getCreatedBy().getPerson().getLastName() + " " + tmp.getCreatedBy().getPerson().getMiddleName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellExpenseIn.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellExpenseIn.setColspan(1);
                    tableExpenseIn.addCell(cellExpenseIn);
                }
                document.add(tableExpenseIn);

                document.add(Chunk.NEWLINE);
            }

            if (resultsExpenseIn != null && !resultsExpenseIn.isEmpty()) {
                for (ExpenseCompany tmp : resultsExpenseIn) {
                    totalExpenseIn = totalExpenseIn + tmp.getAmount().doubleValue();

                }
            }

            if (resultsExpenseOut != null && !resultsExpenseOut.isEmpty()) {
                for (ExpenseCompany tmp : resultsExpenseOut) {
                    totalExpenseOut = totalExpenseOut + tmp.getAmount().doubleValue();

                }
            }

            PdfPTable tablePayroll = new PdfPTable(3);
            tablePayroll.setTotalWidth(new float[]{100, 100, 100});

            tablePayroll.setLockedWidth(true);
            PdfPCell cellPayroll = new PdfPCell(new Paragraph("Nóminas",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellPayroll.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellPayroll.setBackgroundColor(BaseColor.BLUE);
            cellPayroll.setColspan(3);
            tablePayroll.addCell(cellPayroll);

            cellPayroll = new PdfPCell(new Paragraph("Monto",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellPayroll.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellPayroll.setColspan(1);
            tablePayroll.addCell(cellPayroll);

            cellPayroll = new PdfPCell(new Paragraph("Empleado",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellPayroll.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellPayroll.setColspan(1);
            tablePayroll.addCell(cellPayroll);

            cellPayroll = new PdfPCell(new Paragraph("Usuario creación",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellPayroll.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellPayroll.setColspan(1);
            tablePayroll.addCell(cellPayroll);

            if (resultsPayroll != null && !resultsPayroll.isEmpty()) {
                for (Payroll tmp : resultsPayroll) {
                    totalPayroll = totalPayroll + tmp.getTotal();
                    cellPayroll = new PdfPCell(new Paragraph(tmp.getTotal() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellPayroll.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellPayroll.setColspan(1);
                    tablePayroll.addCell(cellPayroll);

                    cellPayroll = new PdfPCell(new Paragraph(tmp.getUser().getPerson().getFirstName() + " " + tmp.getUser().getPerson().getLastName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellPayroll.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellPayroll.setColspan(1);
                    tablePayroll.addCell(cellPayroll);

                    cellPayroll = new PdfPCell(new Paragraph(tmp.getCreatedBy().getPerson().getFirstName() + " " + tmp.getCreatedBy().getPerson().getSecondName() +" "+ tmp.getCreatedBy().getPerson().getLastName() + " " + tmp.getCreatedBy().getPerson().getMiddleName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellPayroll.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellPayroll.setColspan(1);
                    tablePayroll.addCell(cellPayroll);
                }
                document.add(tablePayroll);

                document.add(Chunk.NEWLINE);
            }

            PdfPTable tableTaxes = new PdfPTable(4);
            tableTaxes.setTotalWidth(new float[]{100, 100, 100, 100});

            tableTaxes.setLockedWidth(true);
            PdfPCell cellTaxes = new PdfPCell(new Paragraph("Impuestos",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellTaxes.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTaxes.setBackgroundColor(BaseColor.BLUE);
            cellTaxes.setColspan(4);
            tableTaxes.addCell(cellTaxes);

            cellTaxes = new PdfPCell(new Paragraph("Monto",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTaxes.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTaxes.setColspan(1);
            tableTaxes.addCell(cellTaxes);

            cellTaxes = new PdfPCell(new Paragraph("Tipo",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTaxes.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTaxes.setColspan(1);
            tableTaxes.addCell(cellTaxes);

            cellTaxes = new PdfPCell(new Paragraph("Descripción",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTaxes.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTaxes.setColspan(1);
            tableTaxes.addCell(cellTaxes);

            cellTaxes = new PdfPCell(new Paragraph("Usuario creación",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTaxes.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTaxes.setColspan(1);
            tableTaxes.addCell(cellTaxes);

            if (resultsTaxes != null && !resultsTaxes.isEmpty()) {
                for (Taxes tmp : resultsTaxes) {
                    totalTaxes = totalTaxes + tmp.getAmount().doubleValue();
                    cellTaxes = new PdfPCell(new Paragraph(tmp.getAmount().doubleValue() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellTaxes.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellTaxes.setColspan(1);
                    tableTaxes.addCell(cellTaxes);

                    cellTaxes = new PdfPCell(new Paragraph(tmp.getTaxesType().getLabel(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellTaxes.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellTaxes.setColspan(1);
                    tableTaxes.addCell(cellTaxes);

                    cellTaxes = new PdfPCell(new Paragraph(tmp.getDescription(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellTaxes.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellTaxes.setColspan(1);
                    tableTaxes.addCell(cellTaxes);

                    cellTaxes = new PdfPCell(new Paragraph(tmp.getCreatedBy().getPerson().getFirstName() + " " + tmp.getCreatedBy().getPerson().getSecondName() +" "+ tmp.getCreatedBy().getPerson().getLastName() + " " + tmp.getCreatedBy().getPerson().getMiddleName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellTaxes.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellTaxes.setColspan(1);
                    tableTaxes.addCell(cellTaxes);
                }
                document.add(tableTaxes);

                document.add(Chunk.NEWLINE);
            }

            PdfPTable tableInicios = new PdfPTable(3);
            tableInicios.setTotalWidth(new float[]{100, 100, 100});

            tableTaxes.setLockedWidth(true);
            PdfPCell cellInicios = new PdfPCell(new Paragraph("Inicios",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellInicios.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellInicios.setBackgroundColor(BaseColor.BLUE);
            cellInicios.setColspan(3);
            tableInicios.addCell(cellInicios);

            cellInicios = new PdfPCell(new Paragraph("Monto",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellInicios.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellInicios.setColspan(1);
            tableInicios.addCell(cellInicios);

            cellInicios = new PdfPCell(new Paragraph("Descripción",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellInicios.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellInicios.setColspan(1);
            tableInicios.addCell(cellInicios);

            cellInicios = new PdfPCell(new Paragraph("Usuario",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellInicios.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellInicios.setColspan(1);
            tableInicios.addCell(cellInicios);

            if (resultsInicios != null && !resultsInicios.isEmpty()) {
                for (Expense tmp : resultsInicios) {
                    totalInicios = totalInicios + tmp.getPayment();
                    cellInicios = new PdfPCell(new Paragraph(tmp.getPayment() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellInicios.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellInicios.setColspan(1);
                    tableInicios.addCell(cellInicios);

                    cellInicios = new PdfPCell(new Paragraph(tmp.getDescription(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellInicios.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellInicios.setColspan(1);
                    tableInicios.addCell(cellInicios);

                    cellInicios = new PdfPCell(new Paragraph(tmp.getCreatedBy().getPerson().getFirstName() + " " + tmp.getCreatedBy().getPerson().getSecondName() +" "+ tmp.getCreatedBy().getPerson().getLastName() + " " + tmp.getCreatedBy().getPerson().getMiddleName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellInicios.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellInicios.setColspan(1);
                    tableInicios.addCell(cellInicios);
                }
                document.add(tableInicios);

                document.add(Chunk.NEWLINE);
            }

            PdfPTable tableTransfer = new PdfPTable(5);
            tableTransfer.setTotalWidth(new float[]{100, 100, 100, 100, 100});

            tableTransfer.setLockedWidth(true);
            PdfPCell cellTransfer = new PdfPCell(new Paragraph("Transferencia de dinero",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellTransfer.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTransfer.setBackgroundColor(BaseColor.BLUE);
            cellTransfer.setColspan(5);
            tableTransfer.addCell(cellTransfer);

            cellTransfer = new PdfPCell(new Paragraph("Sucursal emisora",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTransfer.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTransfer.setColspan(1);
            tableTransfer.addCell(cellTransfer);

            cellTransfer = new PdfPCell(new Paragraph("Sucursal receptora",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTransfer.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTransfer.setColspan(1);
            tableTransfer.addCell(cellTransfer);

            cellTransfer = new PdfPCell(new Paragraph("Monto",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTransfer.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTransfer.setColspan(1);
            tableTransfer.addCell(cellTransfer);

            cellTransfer = new PdfPCell(new Paragraph("Descripción",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTransfer.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTransfer.setColspan(1);
            tableTransfer.addCell(cellTransfer);

            cellTransfer = new PdfPCell(new Paragraph("Usuario creación",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTransfer.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTransfer.setColspan(1);
            tableTransfer.addCell(cellTransfer);

            if (resultsTransfer != null && !resultsTransfer.isEmpty()) {
                for (TransferMoneyLocation tmp : resultsTransfer) {
                    if (getLoggedUser().getLocation().getId().equalsIgnoreCase(tmp.getLocationSend().getId())) {
                        totalTransferSend = totalTransferSend + tmp.getAmount();
                    } else {
                        totalTransferReceiver = totalTransferReceiver + tmp.getAmount();
                    }

                    cellTransfer = new PdfPCell(new Paragraph(tmp.getLocationSend().getName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellTransfer.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellTransfer.setColspan(1);
                    tableTransfer.addCell(cellTransfer);

                    cellTransfer = new PdfPCell(new Paragraph(tmp.getLocationReceiver().getName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellTransfer.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellTransfer.setColspan(1);
                    tableTransfer.addCell(cellTransfer);

                    cellTransfer = new PdfPCell(new Paragraph(tmp.getAmount() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellTransfer.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellTransfer.setColspan(1);
                    tableTransfer.addCell(cellTransfer);

                    cellTransfer = new PdfPCell(new Paragraph(tmp.getDescription(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellTransfer.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellTransfer.setColspan(1);
                    tableTransfer.addCell(cellTransfer);

                    cellTransfer = new PdfPCell(new Paragraph(tmp.getCreatedBy().getPerson().getFirstName() + " " + tmp.getCreatedBy().getPerson().getSecondName() +" "+ tmp.getCreatedBy().getPerson().getLastName() + " " + tmp.getCreatedBy().getPerson().getMiddleName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellTransfer.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellTransfer.setColspan(1);
                    tableTransfer.addCell(cellTransfer);
                }
                document.add(tableTransfer);

                document.add(Chunk.NEWLINE);
            }

            PdfPTable tableAdelantos = new PdfPTable(4);
            tableAdelantos.setTotalWidth(new float[]{100, 100, 100, 100});

            tableAdelantos.setLockedWidth(true);
            PdfPCell cellAdelantos = new PdfPCell(new Paragraph("Adelantos",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellAdelantos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellAdelantos.setBackgroundColor(BaseColor.BLUE);
            cellAdelantos.setColspan(4);
            tableAdelantos.addCell(cellAdelantos);

            cellAdelantos = new PdfPCell(new Paragraph("Empleado",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellAdelantos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellAdelantos.setColspan(1);
            tableAdelantos.addCell(cellAdelantos);

            cellAdelantos = new PdfPCell(new Paragraph("Monto",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellAdelantos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellAdelantos.setColspan(1);
            tableAdelantos.addCell(cellAdelantos);

            cellAdelantos = new PdfPCell(new Paragraph("Descripción",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellAdelantos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellAdelantos.setColspan(1);
            tableAdelantos.addCell(cellAdelantos);

            cellAdelantos = new PdfPCell(new Paragraph("Usuario creación",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellAdelantos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellAdelantos.setColspan(1);
            tableAdelantos.addCell(cellAdelantos);

            if (resultsAdelantos != null && !resultsAdelantos.isEmpty()) {
                for (Adelantos tmp : resultsAdelantos) {
                    totalAdelantos = totalAdelantos + tmp.getAmount();
                    cellAdelantos = new PdfPCell(new Paragraph(tmp.getEmployee().getFirstName() + " " + tmp.getEmployee().getLastName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellAdelantos.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellAdelantos.setColspan(1);
                    tableAdelantos.addCell(cellAdelantos);

                    cellAdelantos = new PdfPCell(new Paragraph(tmp.getAmount() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellAdelantos.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellAdelantos.setColspan(1);
                    tableAdelantos.addCell(cellAdelantos);

                    cellAdelantos = new PdfPCell(new Paragraph(tmp.getComment(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellAdelantos.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellAdelantos.setColspan(1);
                    tableAdelantos.addCell(cellAdelantos);

                    cellAdelantos = new PdfPCell(new Paragraph(tmp.getCreatedBy().getPerson().getFirstName() + " " + tmp.getCreatedBy().getPerson().getSecondName() +" "+ tmp.getCreatedBy().getPerson().getLastName() + " " + tmp.getCreatedBy().getPerson().getMiddleName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellAdelantos.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellAdelantos.setColspan(1);
                    tableAdelantos.addCell(cellAdelantos);
                }
                document.add(tableAdelantos);

                document.add(Chunk.NEWLINE);
            }

            PdfPTable tableSanction = new PdfPTable(4);
            tableSanction.setTotalWidth(new float[]{100, 100, 100, 100});

            tableSanction.setLockedWidth(true);
            PdfPCell cellSanction = new PdfPCell(new Paragraph("Disposiciones de ahorro y préstamos a empleados",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellSanction.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSanction.setBackgroundColor(BaseColor.BLUE);
            cellSanction.setColspan(4);
            tableSanction.addCell(cellSanction);

            cellSanction = new PdfPCell(new Paragraph("Empleado",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellSanction.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSanction.setColspan(1);
            tableSanction.addCell(cellSanction);

            cellSanction = new PdfPCell(new Paragraph("Monto",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellSanction.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSanction.setColspan(1);
            tableSanction.addCell(cellSanction);

            cellSanction = new PdfPCell(new Paragraph("Tipo",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellSanction.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSanction.setColspan(1);
            tableSanction.addCell(cellSanction);

            cellSanction = new PdfPCell(new Paragraph("Usuario creación",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellSanction.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSanction.setColspan(1);
            tableSanction.addCell(cellSanction);

            if (resultsSanction != null && !resultsSanction.isEmpty()) {
                for (EmployeeSanction tmp : resultsSanction) {
                    totalSanction = totalSanction + tmp.getPayment();
                    cellSanction = new PdfPCell(new Paragraph(tmp.getEmployee().getFirstName() + " " + tmp.getEmployee().getLastName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellSanction.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellSanction.setColspan(1);
                    tableSanction.addCell(cellSanction);

                    cellSanction = new PdfPCell(new Paragraph(tmp.getPayment() + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellSanction.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellSanction.setColspan(1);
                    tableSanction.addCell(cellSanction);

                    cellSanction = new PdfPCell(new Paragraph(tmp.getType().getType(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellSanction.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellSanction.setColspan(1);
                    tableSanction.addCell(cellSanction);

                    cellSanction = new PdfPCell(new Paragraph(tmp.getCreatedBy().getPerson().getFirstName() + " " + tmp.getCreatedBy().getPerson().getSecondName() +" "+ tmp.getCreatedBy().getPerson().getLastName() + " " + tmp.getCreatedBy().getPerson().getMiddleName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellSanction.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellSanction.setColspan(1);
                    tableSanction.addCell(cellSanction);
                }
                document.add(tableSanction);

                document.add(Chunk.NEWLINE);
            }

            PdfPTable tableSaleDeposit = new PdfPTable(4);
            tableSaleDeposit.setTotalWidth(new float[]{100, 100, 100, 100});

            tableSaleDeposit.setLockedWidth(true);
            PdfPCell cellSaleDeposit = new PdfPCell(new Paragraph("Ventas por depósito",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSaleDeposit.setBackgroundColor(BaseColor.BLUE);
            cellSaleDeposit.setColspan(4);
            tableSaleDeposit.addCell(cellSaleDeposit);

            cellSaleDeposit = new PdfPCell(new Paragraph("Chofer",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSaleDeposit.setColspan(1);
            tableSaleDeposit.addCell(cellSaleDeposit);

            cellSaleDeposit = new PdfPCell(new Paragraph("Monto",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSaleDeposit.setColspan(1);
            tableSaleDeposit.addCell(cellSaleDeposit);

            cellSaleDeposit = new PdfPCell(new Paragraph("Fecha",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSaleDeposit.setColspan(1);
            tableSaleDeposit.addCell(cellSaleDeposit);

            cellSaleDeposit = new PdfPCell(new Paragraph("Usuario creación",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSaleDeposit.setColspan(1);
            tableSaleDeposit.addCell(cellSaleDeposit);

            if (saleDeposit != null && !saleDeposit.isEmpty()) {
                for (Sale tmp : saleDeposit) {
                    cellSaleDeposit = new PdfPCell(new Paragraph(tmp.getPerson().getFirstName() + " " + tmp.getPerson().getLastName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellSaleDeposit.setColspan(1);
                    tableSaleDeposit.addCell(cellSaleDeposit);

                    cellSaleDeposit = new PdfPCell(new Paragraph((tmp.getPayDay() + tmp.getPaySaving() + tmp.getAccident()) + "",
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellSaleDeposit.setColspan(1);
                    tableSaleDeposit.addCell(cellSaleDeposit);

                    cellSaleDeposit = new PdfPCell(new Paragraph(tmp.getCreatedOn().toString(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellSaleDeposit.setColspan(1);
                    tableSaleDeposit.addCell(cellSaleDeposit);

                    cellSaleDeposit = new PdfPCell(new Paragraph(tmp.getCreatedBy().getPerson().getFirstName() + " " + tmp.getCreatedBy().getPerson().getSecondName() +" "+ tmp.getCreatedBy().getPerson().getLastName() + " " + tmp.getCreatedBy().getPerson().getMiddleName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellSaleDeposit.setColspan(1);
                    tableSaleDeposit.addCell(cellSanction);
                }
                document.add(tableSaleDeposit);

                document.add(Chunk.NEWLINE);
            }

            PdfPTable tableTotal = new PdfPTable(11);
            tableTotal.setTotalWidth(new float[]{60, 35, 45, 55, 50, 45, 45, 65, 65, 50, 60});

            tableTotal.setLockedWidth(true);
            PdfPCell cellTotal = new PdfPCell(new Paragraph("Totales",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setBackgroundColor(BaseColor.BLUE);
            cellTotal.setColspan(11);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Cuadre anterior",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Cortes",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Entradas",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Gastos admon.",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Nóminas",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Impuestos",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Inicios",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Transferencias enviadas",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Transferencias recibidas",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Adelantos",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph("Mov. empleados",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(lastStable.doubleValue() + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalCortes + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalExpenseIn + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalExpenseOut + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalPayroll + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalTaxes + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalInicios + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalTransferSend + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalTransferReceiver + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalAdelantos + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            cellTotal = new PdfPCell(new Paragraph(totalSanction + "",
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellTotal.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellTotal.setColspan(1);
            tableTotal.addCell(cellTotal);

            document.add(tableTotal);

            document.add(Chunk.NEWLINE);

            PdfPTable tableStable = new PdfPTable(9);
            tableStable.setTotalWidth(new float[]{50, 50, 60, 60, 60, 50, 50, 65, 100});

            tableStable.setLockedWidth(true);
            PdfPCell cellStable = new PdfPCell(new Paragraph("Cuadre de caja general",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setBackgroundColor(BaseColor.BLUE);
            cellStable.setColspan(9);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph("Fecha creación",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph("Usuario",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph("Total en caja",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph("Banco",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph("Deje en sobres",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph("Efectivo",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph("Monedas",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph("Diferencia",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph("Descripción",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            String date = formatter.format(selectedRow.getCreatedOn());

            cellStable = new PdfPCell(new Paragraph(date,
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph(userTmp.getPerson().getFirstName() + " "+ userTmp.getPerson().getSecondName() +" " + userTmp.getPerson().getLastName() + " " + userTmp.getPerson().getMiddleName(),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph(selectedRow.getTotalGeneralBox().toString(),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph(selectedRow.getTotalBank().toString(),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph(selectedRow.getTotalEnvelope().toString(),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph(selectedRow.getTotalBankNote().toString(),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph(selectedRow.getTotalCoin().toString(),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph((selectedRow.getTotalStable().subtract(selectedRow.getTotalGeneralBox())).toString(),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph(selectedRow.getDescription(),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            document.add(tableStable);

            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            document.add(new Paragraph("                  __________________________                 __________________________"));
            document.add(new Paragraph("                                      Firma                                      Nombre y firma del revisor"));
            document.add(new Paragraph("                                " + userTmp.getPerson().getFirstName() + " "+ userTmp.getPerson().getSecondName() +" " + userTmp.getPerson().getLastName() + " " + userTmp.getPerson().getMiddleName()));

        } catch (Exception e) {
            System.out.print("Error 1: " + e.getMessage());
        }

        document.close();
        FacesContext context = FacesContext.getCurrentInstance();
        Object response = context.getExternalContext().getResponse();
        if (response instanceof HttpServletResponse) {
            HttpServletResponse hrs = (HttpServletResponse) response;
            hrs.setContentType("application/pdf");
            hrs.setHeader("Content-disposition", "attachment");
            hrs.setContentLength(baos.size());
            try {
                ServletOutputStream out = hrs.getOutputStream();
                baos.writeTo(out);
                out.flush();

            } catch (IOException e) {
                System.out.print("Error 2: " + e.getMessage());
            }
            context.responseComplete();
        }
    }

    /**
     * Clean add new stable general box entry form.
     */
    public void cleanForm() {
        try {
            getStableGeneralBox().setTotalGeneralBox(getController().getTotalInBox(getLoggedUser().getLocation().getId()));
            getStableGeneralBox().setTotalCoin(BigDecimal.ZERO);
            getStableGeneralBox().setTotalBankNote(BigDecimal.ZERO);
            getStableGeneralBox().setTotalBank(BigDecimal.ZERO);
            getStableGeneralBox().setTotalEnvelope(BigDecimal.ZERO);
            getStableGeneralBox().setCreatedOn(new Date());
            getStableGeneralBox().setTotalStable(BigDecimal.ZERO);
            getStableGeneralBox().setDescription(null);
        } catch (Exception e) {
            logger.error("cleanForm", e);
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("stable.general.box"),
                    getBundlePropertyFile().getString("stable.general.box.clean.form.error"));
        }
    }

    /**
     *
     */
    public void calculateDifference() {
        try {
            getStableGeneralBox().setTotalStable(getStableGeneralBox().getTotalCoin()
                    .add(getStableGeneralBox().getTotalBankNote())
                    .add(getStableGeneralBox().getTotalBank())
                    .add(getStableGeneralBox().getTotalEnvelope())
                    .subtract(getStableGeneralBox().getTotalGeneralBox()));
        } catch (Exception e) {
            logger.error("calculateDifference", e);
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("stable.general.box"),
                    getBundlePropertyFile().getString("stable.general.box.calculate.difference.error"));
        }
    }

    /**
     * Update stable general box list between start date and end date.
     */
    public void updateHistoryStableGeneralBoxList() {
        logger.info("updateHistoryStableGeneralBoxList");
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("stable.general.box"),
                        getBundlePropertyFile().getString("start.date.after.error"));
            } else {
                setUpDates(false);
                setHistoryStableGeneralBox(
                        getController().findStableGeneralBoxBetweenDates(
                                getStartDate(),
                                getEndDate(),
                                getLoggedUser().getLocation().getId()
                        )
                );
            }
        } catch (Exception e) {
            logger.error("updateHistoryStableGeneralBoxList", e);
        }
    }

    @Override
    public void editRow(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void onRowCancel(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void onRowReorder(ReorderEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void addRow() {
        logger.info("addRow");
        try {

            if (getGenericController().existExpenseCompanyInDepositPending(getLoggedUser().getLocation().getId())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Deposistos en ventas",
                        "Los depositos de entradas deben estar aceptados");
                return;
            }
            
            if (getGenericController().existExpenseCompanyOutDepositPending(getLoggedUser().getLocation().getId())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Deposistos en ventas",
                        "Los depositos de gastos administrativos deben estar aceptados");
                return;
            }

            
            if (getGenericController().existTaxesDepositPending(getLoggedUser().getLocation().getId())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Deposistos en ventas",
                        "Los depositos impuestos deben estar aceptados");
                return;
            }

            if (getGenericController().isReadyToDoADailyCash(getLoggedUser().getLocation().getId())) {
                if (getController().existStableGeneralBoxEqToDate(getCreatedOn(), getLoggedUser().getLocation().getId())) {
                    logger.error("Date: " + getCreatedOn() + " already exist");

                    showMessage(FacesMessage.SEVERITY_ERROR,
                            getBundlePropertyFile().getString("stable.general.box"),
                            getBundlePropertyFile().getString("stable.general.box.add.already.exist.exception.desc"));
                } else {
                    if (getStableGeneralBox().getTotalGeneralBox().compareTo(getController().getTotalInBox(getLoggedUser().getLocation().getId())) != 0) {
                        showMessage(FacesMessage.SEVERITY_ERROR,
                                "Advertencia",
                                "Otros usuarios han movido la información de caja general, por lo cual cambio el monto. Favor de refrescar la página.");
                        return;
                    }
                    getStableGeneralBox().setId(UUID.randomUUID().toString());
                    getStableGeneralBox().setActiveStatus(BasicType.ENEBLED);
                    getStableGeneralBox().setCreatedBy(getLoggedUser());
                    getStableGeneralBox().setCreatedOn(getCreatedOn());
                    getStableGeneralBox().setLocation(getLoggedUser().getLocation());

                    BigDecimal newTotalToUpdate = (getStableGeneralBox().getTotalBankNote())
                            .add(getStableGeneralBox().getTotalBank())
                            .add(getStableGeneralBox().getTotalCoin())
                            .add(getStableGeneralBox().getTotalEnvelope());

                    getStableGeneralBox().setTotalStable(newTotalToUpdate);

                    if (getController().saveStableGeneralBox(getStableGeneralBox())) {

                        if (isUserInRoleBeanInBackground("admin.stable.general.box.name")
                                || isUserInRoleBeanInBackground("admin.stable.general.box.delete")) {
                            setUpDates(false);
                            setHistoryStableGeneralBox(
                                    getController().findStableGeneralBoxBetweenDates(
                                            getStartDate(),
                                            getEndDate(),
                                            getLoggedUser().getLocation().getId()
                                    )
                            );

                            if (getStableGeneralBox().getTotalGeneralBox().compareTo(getStableGeneralBox().getTotalStable()) < 0) {
                                Date dt = new Date();
                                Calendar c = Calendar.getInstance();
                                c.setTime(dt);
                                c.add(Calendar.DATE, 1);
                                dt = c.getTime();

                                ExpenseCompany ec = new ExpenseCompany(
                                        UUID.randomUUID().toString(),
                                        getStableGeneralBox().getTotalStable().subtract(getStableGeneralBox().getTotalGeneralBox()),
                                        "Creada automaticamente por sobrante de caja general",
                                        ExpenseCompanyType.PAYMENT_IN,
                                        BasicType.ENEBLED,
                                        new User(getLoggedUser().getId(), ""),
                                        dt,
                                        getLoggedUser().getLocation());

                                if (getInController().saveExpenseCompany(ec)) {
                                    showMessage(FacesMessage.SEVERITY_INFO,
                                            "Entrada por sobrante",
                                            "Se creó la entrada por sobrante de forma correcta");
                                }

                            }   
                            
                           // se envia correo electronico
                           setEmail(getStableGeneralBox());
                            
                        }

                        initStableGeneralBoxObject();

                        showMessage(FacesMessage.SEVERITY_INFO,
                                getBundlePropertyFile().getString("stable.general.box"),
                                getBundlePropertyFile().getString("stable.general.box.add.success.desc"));

                    } else {
                        logger.error("Stable general box couldnot saved");
                        showMessage(FacesMessage.SEVERITY_ERROR,
                                getBundlePropertyFile().getString("stable.general.box"),
                                getBundlePropertyFile().getString("stable.general.box.add.exception.desc"));
                    }
                }
            } else {
                logger.error("Exists users without daily chash");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Caja general",
                        getBundlePropertyFile().getString("stable.small.box.not.ready.exception.desc"));
            }
        } catch (Exception e) {
            logger.error("addRow", e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("stable.general.box"),
                    getBundlePropertyFile().getString("stable.general.box.add.exception.desc"));
        }
    }
    
    private boolean setEmail(StableGeneralBox sgb) {
        logger.info("setCheckEmail");
        String ACCESS_KEY = getBundlePropertyFile().getString("aws.access.key");
        String SECRET_KEY = getBundlePropertyFile().getString("aws.secret.access.key");
        // se valida si la locasion tiene un correo asociado
        if(getLoggedUser().getLocation().getMail()!=null){
            // Remitente y destinatario
            String sender = "soporte@crovonline.com";
            String recipient = getLoggedUser().getLocation().getMail();
            // Configurar credenciales de AWS
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
            AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
                    .withRegion(getBundlePropertyFile().getString("aws.region")) // Cambia la región según tus necesidades
                    .build();

            String SUBJECT = "CROV Inmobiliaria";
            
            String HTMLBODY = "<html>"
                + "<head>"
                + "<style>"
                + "h1 {font-size: 24px; font-weight: bold;}"
                + "p {font-size: 16px;}"
                + "</style>"
                + "</head>"
                + "<body>"
                + "<h1>Cuadre de caja general CROV Inmobiliaria</h1>"
                + "<p>CD - Caja general - " + getLoggedUser().getLocation().getName() + "</p>"
                + "<p>Por entregar: " + currencyFormatNumber(sgb.getTotalGeneralBox()) + "</p>"
                + "<p>Entregado: " + currencyFormatNumber(sgb.getTotalStable()) + "</p>"
                + "<p>Diferencia: " + currencyFormatNumber(sgb.getTotalGeneralBox().subtract(sgb.getTotalStable())) + "</p>"
                + "<p>Comentario: " + sgb.getDescription() + "</p>"
                + "<p>Cuadre realizado por: " + sgb.getCreatedBy().getPerson().getFirstName() + " " + sgb.getCreatedBy().getPerson().getSecondName() + " " + sgb.getCreatedBy().getPerson().getLastName() + " " + sgb.getCreatedBy().getPerson().getMiddleName() + "</p>"
                + "</body>"
                + "</html>";


            String TEXTBODY = "Este mensaje ha sido enviado automáticamente desde CROV Inmobiliaria.\n\n";

            // Crear el mensaje
            SendEmailRequest request = new SendEmailRequest()
                    .withDestination(new Destination().withToAddresses(recipient))
                    .withMessage(new Message()
                            .withBody(new Body()
                                    .withHtml(new Content()
                                            .withCharset("UTF-8").withData(HTMLBODY))
                                    .withText(new Content()
                                            .withCharset("UTF-8").withData(TEXTBODY)))
                            .withSubject(new Content()
                                    .withCharset("UTF-8").withData(SUBJECT)))
                    .withSource(sender);

            // Enviar el correo
            try {
                SendEmailResult result = client.sendEmail(request);
                showMessage(FacesMessage.SEVERITY_INFO, "El correo se ha enviado correctamente", "El correo se ha enviado correctamente");
                logger.info("El correo se ha enviado correctamente. ID del mensaje: " + result.getMessageId());
                return true;
            } catch (AmazonServiceException ex) {
                showMessage(FacesMessage.SEVERITY_ERROR, "Error al enviar el correo", "Error al enviar el correo");
                logger.error("Error al enviar el correo: " + ex.getMessage());
                return false;
            }
        }else{
            showMessage(FacesMessage.SEVERITY_ERROR, "Error al enviar el correo", "Error al enviar el email no ahí un correo asociado a la locación");
            logger.error("Error al enviar el email no ahí un correo asociado a la locación ");
            return false;
        }        
    }

    @Override
    public void deleteRow() {
        logger.info("deleteRow");
        try {
            if (getController().existNextPaidStableGeneralBoxByCreatedOn(getSelectedRow().getCreatedOn(), getLoggedUser().getLocation().getId())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        getBundlePropertyFile().getString("stable.general.box"),
                        getBundlePropertyFile().getString("stable.general.box.delete.not.allow.exception.desc"));
            } else {
                if (getController().updateStableGeneralBoxById(getSelectedRow().getId(), BasicType.DISABLED, getLoggedUser())) {

                    if (null == getCommentsBitacora() || getCommentsBitacora().trim().equals("")) {
                        setCommentsBitacora("El usuario " + getLoggedUser().getUserName() + " no agrego comentarios a la hora de borrar este corte caja general");
                    }

                    String actionBitacora = "Eliminar corte de caja general";
                    String descBitacora = "Se eliminó el corte de caja general con total en caja " + currencyFormatNumber(getSelectedRow().getTotalGeneralBox())
                            + ", total banco " + currencyFormatNumber(getSelectedRow().getTotalBank())
                            + ", total sobre " + currencyFormatNumber(getSelectedRow().getTotalEnvelope())
                            + ", total monedas " + currencyFormatNumber(getSelectedRow().getTotalCoin())
                            + ", total efectivo " + currencyFormatNumber(getSelectedRow().getTotalBankNote())
                            + ", diferencia de " + currencyFormatNumber(getSelectedRow().getTotalGeneralBox().subtract(getSelectedRow().getTotalEnvelope()).subtract(getSelectedRow().getTotalCoin()).subtract(getSelectedRow().getTotalBankNote()))
                            + " y fecha " + getSelectedRow().getCreatedOn();

                    getBitacoraController().saveNewRecordInBitacora(createNewRecordInBitacora(UUID.randomUUID().toString(), actionBitacora, getCommentsBitacora(), descBitacora),
                            getLoggedUser().getLocation().getId());
                    getHistoryStableGeneralBox().remove(getSelectedRow());

                    setSelectedRow(null);
                    setCommentsBitacora("");

                    showMessage(FacesMessage.SEVERITY_INFO,
                            getBundlePropertyFile().getString("stable.general.box"),
                            getBundlePropertyFile().getString("stable.general.box.delete.success.desc"));
                } else {
                    showMessage(FacesMessage.SEVERITY_ERROR,
                            getBundlePropertyFile().getString("stable.general.box"),
                            getBundlePropertyFile().getString("stable.general.box.delete.exception.desc"));
                }
            }
        } catch (Exception e) {
            logger.error("deleteRow", e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("stable.general.box"),
                    getBundlePropertyFile().getString("stable.general.box.delete.exception.desc"));
        }
    }

    /**
     * Setup start date and end date.
     *
     * @param init True if comes from @PostConstruct otherwise false.
     */
    private void setUpDates(boolean init) {
        Calendar startCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();

        if (!init) {
            startCalendar.setTime(getStartDate());
            endCalendar.setTime(getEndDate());
        } else {
            startCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            endCalendar.setTime(new Date());
        }

        startCalendar.add(Calendar.HOUR_OF_DAY, 2);
        startCalendar.add(Calendar.MINUTE, 0);
        startCalendar.add(Calendar.SECOND, 0);
        startCalendar.add(Calendar.MILLISECOND, 0);

        endCalendar.add(Calendar.HOUR_OF_DAY, 22);
        endCalendar.add(Calendar.MINUTE, 59);
        endCalendar.add(Calendar.SECOND, 59);
        endCalendar.add(Calendar.MILLISECOND, 0);

        setStartDate(startCalendar.getTime());
        setEndDate(endCalendar.getTime());
    }

    private void initStableGeneralBoxObject() {
        logger.info("initStableGeneralBoxObject");
        try {
            setStableGeneralBox(new StableGeneralBox());

            getStableGeneralBox().setTotalGeneralBox(getController().getTotalInBox(getLoggedUser().getLocation().getId()));
            getStableGeneralBox().setTotalCoin(BigDecimal.ZERO);
            getStableGeneralBox().setTotalBankNote(BigDecimal.ZERO);
            getStableGeneralBox().setTotalBank(BigDecimal.ZERO);
            getStableGeneralBox().setTotalEnvelope(BigDecimal.ZERO);
            getStableGeneralBox().setTotalStable(BigDecimal.ZERO.subtract(getStableGeneralBox().getTotalGeneralBox()));
            getStableGeneralBox().setCreatedOn(new Date());
        } catch (Exception e) {
            logger.error("initStableGeneralBoxObject", e);
        }

    }

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();

            setController(new StableGeneralBoxController());
            setInController(new ExpenseCompanyController());
            setBitacoraController(new BitacoraController());
            setGenericController(new GenericValidationController());

            setLastStableGeneralBox(getGenericController().lastStableGeneralBoxByDate(getLoggedUser()));

            setCreatedOn(new Date());

            if (isUserInRoleBeanInBackground("admin.stable.general.box.add")) {
                initStableGeneralBoxObject();
            }

            if (isUserInRoleBeanInBackground("admin.stable.general.box.name")
                    || isUserInRoleBeanInBackground("admin.stable.general.box.delete")) {
                setUpDates(true);
                setHistoryStableGeneralBox(
                        getController().findStableGeneralBoxBetweenDates(
                                getStartDate(),
                                getEndDate(),
                                getLoggedUser().getLocation().getId()
                        )
                );
            }

        } catch (Exception e) {
            logger.error(e);
        }
    }

    private StableGeneralBoxController controller;
    private ExpenseCompanyController inController;
    private List<StableGeneralBox> historyStableGeneralBox;
    private StableGeneralBox selectedRow;
    private Date startDate;
    private Date endDate;
    private Date createdOn;
    private StableGeneralBox stableGeneralBox;
    private BigDecimal zero;
    private BitacoraController bitacoraController;
    private String commentsBitacora;

    private GenericValidationController genericController;
    private Date lastStableGeneralBox;

    public GenericValidationController getGenericController() {
        return genericController;
    }

    public void setGenericController(GenericValidationController genericController) {
        this.genericController = genericController;
    }

    public Date getLastStableGeneralBox() {
        return lastStableGeneralBox;
    }

    public void setLastStableGeneralBox(Date lastStableGeneralBox) {
        this.lastStableGeneralBox = lastStableGeneralBox;
    }

    public ExpenseCompanyController getInController() {
        return inController;
    }

    public void setInController(ExpenseCompanyController inController) {
        this.inController = inController;
    }

    public StableGeneralBoxController getController() {
        return controller;
    }

    public void setController(StableGeneralBoxController controller) {
        this.controller = controller;
    }

    public List<StableGeneralBox> getHistoryStableGeneralBox() {
        return historyStableGeneralBox;
    }

    public void setHistoryStableGeneralBox(List<StableGeneralBox> historyStableGeneralBox) {
        this.historyStableGeneralBox = historyStableGeneralBox;
    }

    public StableGeneralBox getSelectedRow() {
        return selectedRow;
    }

    public void setSelectedRow(StableGeneralBox selectedRow) {
        this.selectedRow = selectedRow;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    public StableGeneralBox getStableGeneralBox() {
        return stableGeneralBox;
    }

    public void setStableGeneralBox(StableGeneralBox stableGeneralBox) {
        this.stableGeneralBox = stableGeneralBox;
    }

    public BigDecimal getZero() {
        if (null == zero) {
            zero = BigDecimal.ZERO;
        }
        return zero;
    }

    public void setZero(BigDecimal zero) {
        this.zero = zero;
    }

    public BitacoraController getBitacoraController() {
        return bitacoraController;
    }

    public void setBitacoraController(BitacoraController bitacoraController) {
        this.bitacoraController = bitacoraController;
    }

    public String getCommentsBitacora() {
        return commentsBitacora;
    }

    public void setCommentsBitacora(String commentsBitacora) {
        this.commentsBitacora = commentsBitacora;
    }

    private static final long serialVersionUID = 4735474224887176743L;
    final Logger logger = LogManager.getLogger(StableGeneralBoxBean.class);
}
