/*
 * 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.arrebol.apc.controller.BitacoraController;
import com.arrebol.apc.controller.GenericController;
import com.arrebol.apc.controller.GenericValidationController;
import com.arrebol.apc.controller.admin.StableSmallBoxController;
import com.arrebol.apc.model.admin.OtherExpense;
import com.arrebol.apc.model.admin.StableSmallBox;
import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.enums.ActiveStatus;
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.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 org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 */
@Named("stableSmallBoxManager")
@ViewScoped
public class StableSmallBoxBean 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 {
                setStableSmallBox(fillDatatableStableSmallBox());
            }
        } catch (Exception e) {
        }
    }

    public List<StableSmallBox> fillDatatableStableSmallBox() {
        return getStableSmallBoxCtrl().fillStableSmallBoxDatatable(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.findAllSmallBox(getLoggedUser().getOffice().getId());
        if (totalBox.compareTo(totalBoxTemp) != 0) {
            FacesMessage msg = new FacesMessage("Advertencia", "Otros usuarios han movido la información de caja chica, 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 (stableSmallBoxCtrl.getCountStableSmallBoxByOfficeAndDate(calendar.getTime(), getLoggedUser().getOffice().getId()) > 0) {
            FacesMessage msg = new FacesMessage("Cuadre de caja chica encontrado.", "Ya se encuentra registrado un cuadre de caja chica para ese día.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return;
        }

        if (stableSmallBoxCtrl.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;
        }
        
        Date date = new Date();
        if (genericCtrl.existStableGeneralBoxByCreatedOn(date)) {
            showMessage(FacesMessage.SEVERITY_WARN, "Día cerrado", "No se pueden agregar más cortes de caja chica porque ya se existe un cuadre de caja general de hoy.");
            return;
        }
        StableSmallBox box = new StableSmallBox();
        box.setActiveStatus(ActiveStatus.ENEBLED);
        box.setDescription(description);
        box.setOffice(new Office(getLoggedUser().getOffice().getId()));
        box.setTotalSmallBox(totalBox);
        box.setTotalBankNote(efectivo);
        box.setTotalEnvelope(sobres);
        box.setTotalCoin(monedas);
        BigDecimal temp = sobres.add(efectivo).add(monedas);
        box.setTotalStable(temp.subtract(totalBox));

        try {
            SendMSN msn = new SendMSN("Caja chica - " + "APC" + " - "
                    + "Por entregar: $" + box.getTotalSmallBox().toString() + ", entregado: $"
                    + box.getTotalEnvelope().add(box.getTotalBankNote()).add(box.getTotalCoin()).toString(),
                    SendMSN.getNumberPhoneFormat("3314666450"));
            msn.sendMessage();
        } catch (Exception e) {
            showMessage(FacesMessage.SEVERITY_ERROR,
                    "Error en notificación",
                    "No fue posible enviar el mensaje al receptor, contacta al administrador.");
        }
        
        box.setCreatedOn(new Date());
        box.setCreatedBy(getLoggedUser().getUser().getId());
        stableSmallBoxCtrl.saveStableSmallBox(box);
        efectivo = BigDecimal.ZERO;
        sobres = BigDecimal.ZERO;
        monedas = BigDecimal.ZERO;
        total = BigDecimal.ZERO;
        description = "";
        FacesMessage msg = new FacesMessage("Nuevo cuadre de caja chica", "Se agregó correctamente");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    @Override
    public void deleteRow() {
        try {
            if (stableSmallBoxCtrl.existStableGeneralBoxByCreatedOn(selectedStableSmallBox.getCreatedOn())) {
                showMessage(FacesMessage.SEVERITY_WARN, "Cuadre Caja chica", "No se puede borrar porque ya se realizo el cuadre de caja general del día.");
            } else {
                if (stableSmallBoxCtrl.existNextPaidStableSmallBoxByCreatedOn(selectedStableSmallBox.getCreatedOn())) {
                    showMessage(FacesMessage.SEVERITY_WARN, "Cuadre Caja chica", "No se puede borrar porque existe un cuadre de caja chica posterior");
                } else {
                    boolean delete = true;
                    delete = selectedStableSmallBox.getActiveStatus() == ActiveStatus.ENEBLED ? true : false;

                    if (delete) {

                        stableSmallBoxCtrl.updateStableSmallBoxByStatus(ActiveStatus.DISABLED, selectedStableSmallBox.getId(), getLoggedUser().getUser().getId());
                        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 chica con total en caja " + currencyFormatNumber(getSelectedStableSmallBox().getTotalSmallBox())
                                + ", total sobre " + currencyFormatNumber(getSelectedStableSmallBox().getTotalEnvelope())
                                + ", total monedas " + currencyFormatNumber(getSelectedStableSmallBox().getTotalCoin())
                                + ", total efectivo " + currencyFormatNumber(getSelectedStableSmallBox().getTotalBankNote())
                                + ", diferencia de " + currencyFormatNumber(getSelectedStableSmallBox().getTotalSmallBox().subtract(getSelectedStableSmallBox().getTotalEnvelope()).subtract(getSelectedStableSmallBox().getTotalCoin()).subtract(getSelectedStableSmallBox().getTotalBankNote()))
                                + " y fecha " + getSelectedStableSmallBox().getCreatedOn());
                        bitacoraCtrl.saveBitacora(bitacora);
                        comments = "";

                        searchHistoricalAction();
                        selectedStableSmallBox = null;
                        showMessage(FacesMessage.SEVERITY_INFO, "Cuadre Caja chica", "Se eliminó correctamente.");
                    }
                }
            }

        } catch (Exception e) {
        }
    }

    public StableSmallBoxController getStableSmallBoxCtrl() {
        return stableSmallBoxCtrl;
    }

    public void setStableSmallBoxCtrl(StableSmallBoxController stableSmallBoxCtrl) {
        this.stableSmallBoxCtrl = stableSmallBoxCtrl;
    }

    public List<StableSmallBox> getStableSmallBox() {
        return stableSmallBox;
    }

    public void setStableSmallBox(List<StableSmallBox> stableSmallBox) {
        this.stableSmallBox = stableSmallBox;
    }

    public StableSmallBox getSelectedStableSmallBox() {
        return selectedStableSmallBox;
    }

    public void setSelectedStableSmallBox(StableSmallBox selectedStableSmallBox) {
        this.selectedStableSmallBox = selectedStableSmallBox;
    }

    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<Object> results = new ArrayList<>();
            
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(selectedStableSmallBox.getCreatedOn());
            calendar.add(Calendar.HOUR_OF_DAY, -6);
            Date fecha = calendar.getTime();
            
            results = stableSmallBoxCtrl.getDataReport(fecha);
            List<OtherExpense> gastos = stableSmallBoxCtrl.fillOtherExpenseDatatable(getLoggedUser().getOffice().getId(), selectedStableSmallBox.getCreatedOn(), selectedStableSmallBox.getCreatedOn());
            document.open();

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

            Paragraph printDate = new Paragraph("Fecha de impresión: " + formatter.format(fecha), 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+"/apc_card.png");
            imagen.scalePercent(4f);
            imagen.setAlignment(Element.ALIGN_CENTER);
            document.add(imagen);
            
            Paragraph title = new Paragraph("CORTE DE CAJA CHICA", 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 sobresC = BigDecimal.ZERO;
            BigDecimal efectivoC = BigDecimal.ZERO;
            BigDecimal monedasC = BigDecimal.ZERO;
            BigDecimal totalC = BigDecimal.ZERO;
            BigDecimal dif = BigDecimal.ZERO;

            PdfPTable tableGen = new PdfPTable(5);
            tableGen.setWidthPercentage(100);
            tableGen.setTotalWidth(new float[]{100f, 100f, 110f, 110f, 120f});
            tableGen.setLockedWidth(true);

            PdfPCell cellGen = new PdfPCell(new Paragraph("Detalle de cortes del día",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBackgroundColor(new BaseColor(4, 193, 10));
            cellGen.setColspan(5);
            tableGen.addCell(cellGen);

            cellGen = new PdfPCell(new Paragraph("Asesor",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Ruta",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Monto esperado",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Monto reportado",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Comentarios",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);

            for (Object result : results) {
                Object[] tmp = (Object[]) result;
                // Detalle
                cellGen = new PdfPCell(new Paragraph(tmp[0] == null ? "" : tmp[0].toString(),
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
                cellGen.setColspan(1);
                tableGen.addCell(cellGen);
                //Préstamo anterior
                cellGen = new PdfPCell(new Paragraph(tmp[1] != null ? tmp[1].toString() : "",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
                cellGen.setColspan(1);
                tableGen.addCell(cellGen);
                // Comisión por apertura
                cellGen = new PdfPCell(new Paragraph(tmp[2] != null ? "$" + tmp[2].toString() : "$0.00",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
                cellGen.setColspan(1);
                tableGen.addCell(cellGen);
                // Monto
                cellGen = new PdfPCell(new Paragraph(tmp[3] != null ? "$" + tmp[3].toString() : "$0.00",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
                cellGen.setColspan(1);
                tableGen.addCell(cellGen);
                // Saldo insoluto
                cellGen = new PdfPCell(new Paragraph(tmp[4] != null ? "$" + tmp[4].toString() : "$0.00",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
                cellGen.setColspan(1);
                tableGen.addCell(cellGen);
            }
            document.add(tableGen);
            document.add(new Paragraph("               ", FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.DARK_GRAY)));
            
            PdfPTable tableGastos = new PdfPTable(4);
            tableGastos.setWidthPercentage(100);
            tableGastos.setTotalWidth(new float[]{130f, 130f, 140f, 140f});
            tableGastos.setLockedWidth(true);
            
            PdfPCell cellGastos = new PdfPCell(new Paragraph("Detalle de gastos",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));
            cellGastos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGastos.setBackgroundColor(new BaseColor(4, 193, 10));
            cellGastos.setColspan(5);
            tableGastos.addCell(cellGastos);
            cellGastos = new PdfPCell(new Paragraph("Asesor",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGastos.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGastos.setColspan(1);
            tableGastos.addCell(cellGastos);
            cellGastos = new PdfPCell(new Paragraph("Ruta",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGastos.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGastos.setColspan(1);
            tableGastos.addCell(cellGastos);
            cellGastos = new PdfPCell(new Paragraph("Monto",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGastos.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGastos.setColspan(1);
            tableGastos.addCell(cellGastos);
            cellGastos = new PdfPCell(new Paragraph("Comentarios",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGastos.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGastos.setColspan(1);
            tableGastos.addCell(cellGastos);
            
            for (OtherExpense datoGasto : gastos) {
                // usuario
                cellGastos = new PdfPCell(new Paragraph(datoGasto == null ? "" : datoGasto.getUser().getHumanResource().getFirstName() + " " + datoGasto.getUser().getHumanResource().getLastName(),
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cellGastos.setHorizontalAlignment(Element.ALIGN_LEFT);
                cellGastos.setColspan(1);
                tableGastos.addCell(cellGastos);
                //rutas
                cellGastos = new PdfPCell(new Paragraph(datoGasto != null ? datoGasto.getUserRoutes() : "",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cellGastos.setHorizontalAlignment(Element.ALIGN_LEFT);
                cellGastos.setColspan(1);
                tableGastos.addCell(cellGastos);
                // monto
                cellGastos = new PdfPCell(new Paragraph(datoGasto != null ? "$" + datoGasto.getExpense() : "$0.00",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cellGastos.setHorizontalAlignment(Element.ALIGN_CENTER);
                cellGastos.setColspan(1);
                tableGastos.addCell(cellGastos);
                // comentarios
                cellGastos = new PdfPCell(new Paragraph(datoGasto != null ? datoGasto.getDescription() : "",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cellGastos.setHorizontalAlignment(Element.ALIGN_CENTER);
                cellGastos.setColspan(1);
                tableGastos.addCell(cellGastos);
            }
            
            document.add(tableGastos);
            document.add(new Paragraph("               ", FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.DARK_GRAY)));

            PdfPTable tableRes = new PdfPTable(2);
            tableRes.setTotalWidth(new float[]{100f, 440f});

            tableRes.setLockedWidth(true);
            PdfPCell cellRes = new PdfPCell(new Paragraph("Detalle del cuadre de caja chica",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));
            cellRes.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellRes.setBackgroundColor(new BaseColor(4, 193, 10));
            cellRes.setColspan(2);
            tableRes.addCell(cellRes);

            cellRes = new PdfPCell(new Paragraph("Total caja: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            cellRes = new PdfPCell(new Paragraph(res[5] != null ? "$" + res[5].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            totalC = new BigDecimal(res[5] == null ? "0.0" : res[5].toString());

            cellRes = new PdfPCell(new Paragraph("Total sobres: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            cellRes = new PdfPCell(new Paragraph(res[6] != null ? "$" + res[6].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            sobresC = new BigDecimal(res[6] == null ? "0.0" : res[6].toString());

            cellRes = new PdfPCell(new Paragraph("Total efectivo: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            cellRes = new PdfPCell(new Paragraph(res[7] != null ? "$" + res[7].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            efectivoC = new BigDecimal(res[7] == null ? "0.0" : res[7].toString());

            cellRes = new PdfPCell(new Paragraph("Total monedas: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            cellRes = new PdfPCell(new Paragraph(res[8] != null ? "$" + res[8].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            monedasC = new BigDecimal(res[8] == null ? "0.0" : res[8].toString());

            cellRes = new PdfPCell(new Paragraph("Diferencia: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            dif = sobresC.add(efectivoC).add(monedasC).subtract(totalC);
            cellRes = new PdfPCell(new Paragraph(dif != null ? "$" + dif.toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);

            cellRes = new PdfPCell(new Paragraph("Comentarios: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);
            cellRes = new PdfPCell(new Paragraph(res[10] != null ? res[10].toString() : "",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellRes.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellRes.setBorder(0);
            cellRes.setColspan(1);
            tableRes.addCell(cellRes);

            document.add(tableRes);

            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 cajero responsable"));
//            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");
            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 StableSmallBoxController stableSmallBoxCtrl;
    private GenericController genericCtrl;
    private BitacoraController bitacoraCtrl;
    private GenericValidationController genericValidateController;
    private Date lastStableGeneralBox;
    private String comments;

    private List<StableSmallBox> stableSmallBox;

    private StableSmallBox selectedStableSmallBox;

    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();

        stableSmallBoxCtrl = new StableSmallBoxController();
        genericCtrl = new GenericController();
        bitacoraCtrl = new BitacoraController();
        setGenericValidateController(new GenericValidationController());
        setLastStableGeneralBox(getGenericValidateController().lastStableGeneralBoxByDate(getLoggedUser().getUser()));
        stableSmallBox = fillDatatableStableSmallBox();
        totalBox = genericCtrl.findAllSmallBox(getLoggedUser().getOffice().getId());
        efectivo = BigDecimal.ZERO;
        monedas = BigDecimal.ZERO;
        sobres = BigDecimal.ZERO;
        total = totalBox;
    }

}
