/*
 * 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.apc.web.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.apc.controller.BitacoraController;
import com.arrebol.apc.controller.GenericController;
import com.arrebol.apc.controller.GenericValidationController;
import com.arrebol.apc.controller.admin.StableGeneralBoxController;
import com.arrebol.apc.model.admin.Advance;
import com.arrebol.apc.model.admin.ClosingDay;
import com.arrebol.apc.model.admin.ExpenseCompany;
import com.arrebol.apc.model.admin.MoneyDaily;
import com.arrebol.apc.model.admin.StableGeneralBox;
import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.core.User;
import com.arrebol.apc.model.enums.ActiveStatus;
import com.arrebol.apc.model.enums.ExpenseCompanyType;
import com.arrebol.apc.model.loan.LoanDetails;
import com.arrebol.apc.model.payroll.Payroll;
import com.arrebol.apc.model.system.logs.Bitacora;
import com.arrebol.apc.web.beans.Datatable;
import com.arrebol.apc.web.beans.GenericBean;
import com.arrebol.apc.web.beans.SendMSN;
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.Image;
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.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
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.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import static org.hibernate.annotations.common.util.impl.LoggerFactory.logger;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 */
@Named("stableGeneralBoxManager")
@ViewScoped
public class StableGeneralBoxBean extends GenericBean implements Serializable, Datatable {

    public void searchHistoricalAction() {
        try {
            if (getStarDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                setStableGeneralBox(fillDatatableStableGeneralBox());
            }
        } catch (Exception e) {
        }
    }

    public List<StableGeneralBox> fillDatatableStableGeneralBox() {

        return getStableGeneralBoxCtrl().fillStableGeneralBoxDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate());
    }

    public void calculationFunction() {
        total = sobres.add(efectivo).add(monedas);
        total = total.subtract(totalBox);
    }

    @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) {
        showMessage(FacesMessage.SEVERITY_INFO, "Registro Movido", "De columna: " + (event.getFromIndex() + 1) + " a columna: " + (event.getToIndex() + 1));
    }

    @Override
    public void addRow() {
        if (createdOn == null) {
            FacesMessage msg = new FacesMessage("Datos incorrectos", "La fecha es obligatoria");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return;
        }
        // BigDecimal totalBoxTemp = genericCtrl.findAllGeneralBox(getLoggedUser().getOffice().getId());
        BigDecimal totalBoxTemp = stableGeneralBoxCtrl.getTotalBox();
        
        if (totalBox.compareTo(totalBoxTemp) != 0) {
            FacesMessage msg = new FacesMessage("Advertencia", "Otros usuarios han movido la información de caja general, por lo cual cambio el monto. Favor de refrescar la página.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(createdOn);
        calendar.set(Calendar.HOUR_OF_DAY, 12);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        if (stableGeneralBoxCtrl.getCountStableGeneralBoxByOfficeAndDate(calendar.getTime(), getLoggedUser().getOffice().getId()) > 0) {
            FacesMessage msg = new FacesMessage("Cuadre de caja encontrado.", "Ya se encuentra registrado un cuadre de caja general para ese día.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return;
        }
        
        if (stableGeneralBoxCtrl.getPendingByClosingDay(getLoggedUser().getOffice().getId()).compareTo(BigDecimal.ZERO) > 0) {
            FacesMessage msg = new FacesMessage("ATENCION - CORTES FALTANTES.", "Falta hacer cortes del dia.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return;
        }
        
        StableGeneralBox box = new StableGeneralBox();
        box.setActiveStatus(ActiveStatus.ENEBLED);
        box.setDescription(description);
        box.setOffice(new Office(getLoggedUser().getOffice().getId()));
        box.setTotalGeneralBox(totalBox);
        box.setTotalBankNote(efectivo);
        box.setTotalEnvelope(sobres);
        box.setTotalCoin(monedas);
        BigDecimal temp = sobres.add(efectivo).add(monedas);
        box.setTotalStable(temp.subtract(totalBox));

        box.setCreatedOn(new Date());
        box.setCreatedBy(getLoggedUser().getUser().getId());
        stableGeneralBoxCtrl.saveStableGeneralBox(box);
        
        
        if (total.compareTo(BigDecimal.ZERO) > 0) {
            Calendar calendarDate = calendar;
            calendarDate.add(Calendar.DAY_OF_YEAR, 1);
            Date date = calendarDate.getTime();
            
            ExpenseCompany expense = new ExpenseCompany();
            expense.setActiveStatus(ActiveStatus.ENEBLED);
            expense.setExpenseCompanyType(ExpenseCompanyType.PAYMENT_IN);
            expense.setOffice(new Office(getLoggedUser().getOffice().getId()));
            expense.setAmount(total);
            expense.setDescription("Entrada automática por sobrante de caja general");
            expense.setCreatedOn(date);
            expense.setCreatedBy(box.getCreatedBy());
            
            stableGeneralBoxCtrl.autoSaveEntry(expense);
        }
        
        
        box.setUser(getLoggedUser().getUser());
        setEmail(box);
        
        efectivo = BigDecimal.ZERO;
        sobres = BigDecimal.ZERO;
        monedas = BigDecimal.ZERO;
        total = BigDecimal.ZERO;
        description = "";
        FacesMessage msg = new FacesMessage("Nuevo cuadre de caja general", "Se agregó correctamente");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
    
    private boolean setEmail(StableGeneralBox sgb) {
        
        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
        
            // Remitente y destinatario
            String sender = "crov.technology.services@gmail.com";
            //String recipient = getLoggedUser().getLocation().getMail();
            String recipient = "camposbueno77@gmail.com";
            
            // 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 = "ACE Caja General";
            BigDecimal temp = sgb.getTotalEnvelope().add(sgb.getTotalCoin()).add(sgb.getTotalBankNote());
            String HTMLBODY = "<html>"
                + "<head>"
                + "<style>"
                + "h1 {font-size: 24px; font-weight: bold;}"
                + "p {font-size: 16px;}"
                + "</style>"
                + "</head>"
                + "<body>"
                + "<h1>Cuadre de caja general ACE</h1>"
                + "<p>ACE - Caja general </p>"
               + "<p>Por entregar: " + currencyFormatNumber(sgb.getTotalGeneralBox()) + "</p>"
                + "<p>Entregado: " + currencyFormatNumber(temp) + "</p>"
                + "<p>Diferencia: " + currencyFormatNumber(sgb.getTotalStable()) + "</p>"
                + "<p>Comentario: " + sgb.getDescription() + "</p>"
                + "<p>Cuadre realizado por: " + sgb.getUser().getHumanResource().getFirstName()+" "+sgb.getUser().getHumanResource().getLastName()+"</p>"
                + "</body>"
                + "</html>";


            String TEXTBODY = "Este mensaje ha sido enviado automáticamente desde ACE.\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");
                
                return true;
            } catch (AmazonServiceException ex) {
                showMessage(FacesMessage.SEVERITY_ERROR, "Error al enviar el correo", "Error al enviar el correo");
                
                return false;
            }
          
    }

    @Override
    public void deleteRow() {
        try {
            if (stableGeneralBoxCtrl.existNextPaidStableGeneralBoxByCreatedOn(selectedStableGeneralBox.getCreatedOn())) {
                showMessage(FacesMessage.SEVERITY_WARN, "Historial cadre de caja general", "No se puede borrar porque existe un cuadre de caja posterior.");
            } else {
                boolean delete = true;
                delete = selectedStableGeneralBox.getActiveStatus() == ActiveStatus.ENEBLED ? true : false;

                if (delete) {
                    stableGeneralBoxCtrl.updateStableGeneralBoxByStatus(ActiveStatus.DISABLED, selectedStableGeneralBox.getId(), getLoggedUser().getUser().getId());
                    searchHistoricalAction();
                    Bitacora bitacora = new Bitacora();
                    bitacora.setAction("Eliminar corte de caja general");
                    bitacora.setCommentsUser(getComments());
                    bitacora.setCreatedBy(getLoggedUser().getUser().getId());
                    bitacora.setCreatedOn(new Date());
                    bitacora.setNameUser(getLoggedUser().getUser().getUserName());
                    bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));
                    bitacora.setDescription("Se eliminó el corte de caja general con total en caja " + currencyFormatNumber(getSelectedStableGeneralBox().getTotalGeneralBox())
                            + ", total sobre " + currencyFormatNumber(getSelectedStableGeneralBox().getTotalEnvelope())
                            + ", total monedas " + currencyFormatNumber(getSelectedStableGeneralBox().getTotalCoin())
                            + ", total efectivo " + currencyFormatNumber(getSelectedStableGeneralBox().getTotalBankNote())
                            + ", diferencia de " + currencyFormatNumber(getSelectedStableGeneralBox().getTotalGeneralBox().subtract(getSelectedStableGeneralBox().getTotalEnvelope()).subtract(getSelectedStableGeneralBox().getTotalCoin()).subtract(getSelectedStableGeneralBox().getTotalBankNote()))
                            + " y fecha " + getSelectedStableGeneralBox().getCreatedOn());
                    bitacoraCtrl.saveBitacora(bitacora);
                    comments = "";
                    selectedStableGeneralBox = null;
                    showMessage(FacesMessage.SEVERITY_INFO, "Historial cadre de caja general", "Se eliminó correctamente.");
                }
            }
        } catch (Exception e) {
        }
    }

    public StableGeneralBoxController getStableGeneralBoxCtrl() {
        return stableGeneralBoxCtrl;
    }

    public void setStableGeneralBoxCtrl(StableGeneralBoxController stableGeneralBoxCtrl) {
        this.stableGeneralBoxCtrl = stableGeneralBoxCtrl;
    }

    public List<StableGeneralBox> getStableGeneralBox() {
        return stableGeneralBox;
    }

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

    public StableGeneralBox getSelectedStableGeneralBox() {
        return selectedStableGeneralBox;
    }

    public void setSelectedStableGeneralBox(StableGeneralBox selectedStableGeneralBox) {
        this.selectedStableGeneralBox = selectedStableGeneralBox;
    }

    public BigDecimal getTotalBox() {
        return totalBox;
    }

    public void setTotalBox(BigDecimal totalBox) {
        this.totalBox = totalBox;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public BigDecimal getSobres() {
        return sobres;
    }

    public void setSobres(BigDecimal sobres) {
        this.sobres = sobres;
    }

    public BigDecimal getEfectivo() {
        return efectivo;
    }

    public void setEfectivo(BigDecimal efectivo) {
        this.efectivo = efectivo;
    }

    public BigDecimal getMonedas() {
        return monedas;
    }

    public void setMonedas(BigDecimal monedas) {
        this.monedas = monedas;
    }

    public GenericController getGenericCtrl() {
        return genericCtrl;
    }

    public void setGenericCtrl(GenericController genericCtrl) {
        this.genericCtrl = genericCtrl;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

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

    public BigDecimal getTotal() {
        return total;
    }

    public void setTotal(BigDecimal total) {
        this.total = total;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }
    
    public GenericValidationController getGenericValidateController() {
        return genericValidateController;
    }

    public void setGenericValidateController(GenericValidationController genericController) {
        this.genericValidateController = genericController;
    }
    
    public Date getLastStableGeneralBox() {
        return lastStableGeneralBox;
    }

    public void setLastStableGeneralBox(Date lastStableGeneralBox) {
        this.lastStableGeneralBox = lastStableGeneralBox;
    }
    
    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<MoneyDaily> resultsMoneyDaily = new ArrayList<>();
            List<Advance> resultsAdelantos = new ArrayList<>();
            List<LoanDetails> resultsDepositos = new ArrayList<>();
            

            Double totalCortes = 0D;
            Double totalExpenseIn = 0D;
            Double totalExpenseOut = 0D;
            Double totalPayroll = 0D;
            Double totalInicios = 0D;
            Double totalAdelantos = 0D;
            Double totalDepositos = 0D;
        
            
            List<Object> results = new ArrayList<>();
            

            
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(selectedStableGeneralBox.getCreatedOn());
            calendar.add(Calendar.HOUR_OF_DAY, -6);
            Date fecha = calendar.getTime();
            
            
            Calendar calendarImpresion = Calendar.getInstance();
            calendarImpresion.setTime(new Date());
            calendarImpresion.add(Calendar.HOUR_OF_DAY, -6);
            
            BigDecimal lastStable = BigDecimal.ZERO;
            
            resultsClosing = getStableGeneralBoxCtrl().findClosingDailyListByStableGeneralBox(fecha);
            resultsExpenseIn = getStableGeneralBoxCtrl().findExpenseCompanyInListByStableGeneralBox(fecha);
            resultsExpenseOut = getStableGeneralBoxCtrl().findExpenseCompanyOutListByStableGeneralBox(fecha);
            resultsExpenseAll = getStableGeneralBoxCtrl().findExpenseCompanyAllListByStableGeneralBox(fecha);
            resultsPayroll = getStableGeneralBoxCtrl().findPayrollListByStableGeneralBox(fecha);
            resultsMoneyDaily = getStableGeneralBoxCtrl().findIniciosListByStableGeneralBox(fecha);
            resultsAdelantos = getStableGeneralBoxCtrl().findAdelantosListByStableGeneralBox(fecha);
            resultsDepositos = getStableGeneralBoxCtrl().findLoanDetailsDepositByStableGeneralBox(fecha);
            
            lastStable = getStableGeneralBoxCtrl().getLastStableGeneralBox(fecha);
            
            DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
            
            results = stableGeneralBoxCtrl.getDataReport(fecha);
            document.open();

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

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

            ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
            String carpetaImagen = (String) servletContext.getRealPath("resources/serenity-layout/images");

            Image imagen = Image.getInstance(carpetaImagen + "/ace_logo.jpg");
            imagen.scalePercent(4f);
            imagen.setAlignment(Element.ALIGN_CENTER);
            document.add(imagen);

            Paragraph title = new Paragraph("CUADRE CAJA GENERAL", FontFactory.getFont("arial", 18, Font.BOLD, BaseColor.DARK_GRAY));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);            
            
            document.add(Chunk.NEWLINE);
            
            Object[] res = (Object[]) results.get(0);
            BigDecimal sobresCajaChica = BigDecimal.ZERO;
            BigDecimal efectivoCajaChica = BigDecimal.ZERO;
            BigDecimal monedasCajaChica = BigDecimal.ZERO;
            BigDecimal totalCajaChica = BigDecimal.ZERO;
            
            BigDecimal sobresCajaGral = BigDecimal.ZERO;
            BigDecimal efectivoCajaGral = BigDecimal.ZERO;
            BigDecimal monedasCajaGral = BigDecimal.ZERO;
            BigDecimal totalCajaGral = BigDecimal.ZERO;
            
            PdfPTable tableGen = new PdfPTable(3);
            tableGen.setWidthPercentage(100);
            tableGen.setTotalWidth(new float[]{150f, 205f, 205f});
            tableGen.setLockedWidth(true);
            
            
            
            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(new BaseColor(41, 171, 225));
            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.getAmountPaid().doubleValue();
                    cell = new PdfPCell(new Paragraph(tmp.getUser().getHumanResource().getFirstName() + " " + tmp.getUser().getHumanResource().getLastName(),
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setColspan(1);
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph(df2.format(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(df2.format(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(df2.format((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);

                    Calendar calendarClosing = Calendar.getInstance();
                    calendarClosing.setTime(tmp.getCreatedOn());
                    calendarClosing.add(Calendar.HOUR_OF_DAY, -6);
                    
                    
                    cell = new PdfPCell(new Paragraph(formatter.format(calendarClosing.getTime()),
                            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().getUser().getHumanResource().getFirstName() + " " + tmp.getCreatedBy().getUser().getHumanResource().getLastName(),
                            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(3);
            tableExpenseIn.setTotalWidth(new float[]{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(new BaseColor(41, 171, 225));
            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(df2.format(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.getUser().getUser().getHumanResource().getFirstName() + " " + tmp.getUser().getUser().getHumanResource().getLastName(),
                            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(new BaseColor(41, 171, 225));
            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.getTotalPayment().doubleValue();
                    cellPayroll = new PdfPCell(new Paragraph(df2.format(tmp.getTotalPayment())+ "",
                            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.getHumanResource().getFirstName() + " " + tmp.getHumanResource().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.getUser().getHumanResource().getFirstName() + " " + tmp.getUser().getHumanResource().getLastName(),
                            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 tableInicios = new PdfPTable(2);
            tableInicios.setTotalWidth(new float[]{150,150});

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

            cellInicios.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellInicios.setBackgroundColor(new BaseColor(41, 171, 225));
            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("Usuario",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellInicios.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellInicios.setColspan(1);
            tableInicios.addCell(cellInicios);

            if (resultsMoneyDaily != null && !resultsMoneyDaily.isEmpty()) {
                for (MoneyDaily tmp : resultsMoneyDaily) {
                    totalInicios = totalInicios + tmp.getAmount().doubleValue();
                    cellInicios = new PdfPCell(new Paragraph(df2.format(tmp.getAmount()) + "",
                            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.getUser().getHumanResource().getFirstName() + " " + tmp.getUser().getHumanResource().getLastName(),
                            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 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 (Advance tmp : resultsAdelantos) {
                    totalAdelantos = totalAdelantos + tmp.getAmount().doubleValue();
                    cellAdelantos = new PdfPCell(new Paragraph(tmp.getHumanResource().getFirstName() + " " + tmp.getHumanResource().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(df2.format(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.getUser().getHumanResource().getFirstName() + " " + tmp.getUser().getHumanResource().getLastName(),
                            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 tableSaleDeposit = new PdfPTable(4);
            tableSaleDeposit.setTotalWidth(new float[]{100, 100, 100, 100});

            tableSaleDeposit.setLockedWidth(true);
            PdfPCell cellSaleDeposit = new PdfPCell(new Paragraph("Depositos",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));

            cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellSaleDeposit.setBackgroundColor(new BaseColor(41, 171, 225));
            cellSaleDeposit.setColspan(4);
            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("Cliente",
                    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 (resultsDepositos != null && !resultsDepositos.isEmpty()) {
                for (LoanDetails tmp : resultsDepositos) {
                    

                    cellSaleDeposit = new PdfPCell(new Paragraph(df2.format(tmp.getPaymentAmount()) + "",
                            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.getLoan().getCustomer().getFirstName() + " "+ tmp.getLoan().getCustomer().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.getCreatedOn() + "",
                            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.getUser().getHumanResource().getFirstName() + " "+ tmp.getUser().getHumanResource().getLastName() ,
                            FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                    cellSaleDeposit.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cellSaleDeposit.setColspan(1);
                    tableSaleDeposit.addCell(cellSaleDeposit);
                }
                document.add(tableSaleDeposit);

                document.add(Chunk.NEWLINE);
            }
            
            PdfPTable tableTotal = new PdfPTable(7);
            tableTotal.setTotalWidth(new float[]{60, 45, 45, 55, 50, 45, 45});

            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(new BaseColor(41, 171, 225));
            cellTotal.setColspan(7);
            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("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("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(df2.format(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(df2.format(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(df2.format(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(df2.format(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(df2.format(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(df2.format(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(df2.format(totalAdelantos) + "",
                    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);
            
            
            
            User userTmp = selectedStableGeneralBox.getUser();
            PdfPTable tableStable = new PdfPTable(8);
            tableStable.setTotalWidth(new float[]{50, 50, 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(new BaseColor(41, 171, 225));
            cellStable.setColspan(8);
            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("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);

            Calendar calendarCreatedOn = Calendar.getInstance();
            calendarCreatedOn.setTime(selectedStableGeneralBox.getCreatedOn());
            calendarCreatedOn.add(Calendar.HOUR_OF_DAY, -6);
            
            String date = formatter.format(calendarCreatedOn.getTime());

            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.getHumanResource().getFirstName() + " " + userTmp.getHumanResource().getLastName(),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

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

            

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

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

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

            cellStable = new PdfPCell(new Paragraph(df2.format((selectedStableGeneralBox.getTotalGeneralBox().subtract(selectedStableGeneralBox.getTotalBankNote().add(selectedStableGeneralBox.getTotalEnvelope()).add(selectedStableGeneralBox.getTotalCoin())))),
                    FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
            cellStable.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellStable.setColspan(1);
            tableStable.addCell(cellStable);

            cellStable = new PdfPCell(new Paragraph(selectedStableGeneralBox.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(new Paragraph("                  __________________________                 __________________________"));
            document.add(new Paragraph("                                      Firma                                      Nombre y firma del revisor"));
            document.add(new Paragraph("                          "+ userTmp.getHumanResource().getFirstName() + " " + userTmp.getHumanResource().getLastName() +""));
            //document.add(new Paragraph("                          " + res[8] == null ? "" : res[8].toString()));

        } 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;filename=caja_general.pdf");
            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();
        }
    }
    
    private StableGeneralBoxController stableGeneralBoxCtrl;
    private GenericController genericCtrl;
    private BitacoraController bitacoraCtrl;
    private GenericValidationController genericValidateController;
    private Date lastStableGeneralBox;
    private String comments;

    private List<StableGeneralBox> stableGeneralBox;

    private StableGeneralBox selectedStableGeneralBox;

    private BigDecimal totalBox;

    private String description;
    private BigDecimal sobres;
    private BigDecimal efectivo;
    private BigDecimal monedas;
    private Date createdOn;
    private BigDecimal total;

    @PostConstruct
    public void init() {
        loadBundlePropertyFile();
        initOneWeekBeforeToCurrdate();

        stableGeneralBoxCtrl = new StableGeneralBoxController();
        genericCtrl = new GenericController();
        bitacoraCtrl = new BitacoraController();
        setGenericValidateController(new GenericValidationController());
        setLastStableGeneralBox(getGenericValidateController().lastStableGeneralBoxByDate(getLoggedUser().getUser()));
        stableGeneralBox = fillDatatableStableGeneralBox();
        // totalBox = genericCtrl.findAllGeneralBox(getLoggedUser().getOffice().getId());
        totalBox = stableGeneralBoxCtrl.getTotalBox();
        efectivo = BigDecimal.ZERO;
        monedas = BigDecimal.ZERO;
        sobres = BigDecimal.ZERO;
        total = totalBox;
        createdOn=new Date();
    }

}
