/*
 * 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.StableGeneralBoxController;
import com.arrebol.apc.model.admin.ExpenseCompany;
import com.arrebol.apc.model.admin.StableGeneralBox;
import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.enums.ActiveStatus;
import com.arrebol.apc.model.enums.ExpenseCompanyType;
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 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);
        }
        
        try {
            SendMSN msn = new SendMSN("Caja general - " + "APC" + " - "
                    + "Total: $" + totalBox.toString() + ", Entrego: $"
                    + sobres.add(efectivo).add(monedas).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.");
        }
        
        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);
    }

    @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<Object> results = new ArrayList<>();
                        
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(selectedStableGeneralBox.getCreatedOn());
            calendar.add(Calendar.HOUR_OF_DAY, -6);
            Date fecha = calendar.getTime();
            
            results = stableGeneralBoxCtrl.getDataReport(fecha);
            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("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);
            
            PdfPCell cellGen = new PdfPCell(new Paragraph("Detalle del día de egresos e ingresos",
                    FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.WHITE)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBackgroundColor(new BaseColor( 4, 193, 10 ));
            cellGen.setColspan(3);
            tableGen.addCell(cellGen);
            
            cellGen = new PdfPCell(new Paragraph("Tipo",
                    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("Ingreso",
                    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("Egreso",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // INICIOS
            cellGen = new PdfPCell(new Paragraph("inicios",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Inicios Ingresos
            cellGen = new PdfPCell(new Paragraph("$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Inicios Egresos
            cellGen = new PdfPCell(new Paragraph(res[1] != null ? "$" + res[1].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // ENTRADAS
            cellGen = new PdfPCell(new Paragraph("Entradas",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Entradas Ingresos
            cellGen = new PdfPCell(new Paragraph(res[4] != null ? "$" + res[4].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Entradas Egresos
            cellGen = new PdfPCell(new Paragraph("$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
             // ADELANTOS
            cellGen = new PdfPCell(new Paragraph("Adelantos",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Adelantos Ingresos
            cellGen = new PdfPCell(new Paragraph("$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Adelantos Egresos
            cellGen = new PdfPCell(new Paragraph(res[3] != null ? "$" + res[3].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
             // GASTOS ADMON
            cellGen = new PdfPCell(new Paragraph("Gastos admon.",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Gastos Admon Ingresos
            cellGen = new PdfPCell(new Paragraph("$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Gastos Admon Egresos
            cellGen = new PdfPCell(new Paragraph(res[5] != null ? "$" + res[5].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
             // NOMINA
            cellGen = new PdfPCell(new Paragraph("Nóminas",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Nómina Ingresos
            cellGen = new PdfPCell(new Paragraph("$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            // Nómina Egresos
            cellGen = new PdfPCell(new Paragraph(res[2] != null ? "$" + res[2].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            
            document.add(tableGen);
            document.add(Chunk.NEWLINE);
            
            PdfPTable table = new PdfPTable(4);
            table.setTotalWidth(new float[]{100f, 170f, 140f, 150f});

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

            cell = new PdfPCell(new Paragraph("Total caja chica: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[6] != null ? "$" + res[6].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            totalCajaChica = new BigDecimal(res[6] == null ? "0.0" : res[6].toString());
            cell = new PdfPCell(new Paragraph("Total caja general: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[12] != null ? "$" + res[12].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            totalCajaGral = new BigDecimal(res[12] == null ? "0.0" : res[12].toString());
            
            cell = new PdfPCell(new Paragraph("Total sobres: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[7] != null ? "$" + res[7].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            sobresCajaChica = new BigDecimal(res[7] == null ? "0.0" : res[7].toString());
            cell = new PdfPCell(new Paragraph("Total sobres: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[13] != null ? "$" + res[13].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            sobresCajaGral = new BigDecimal(res[13] == null ? "0.0" : res[13].toString());
            
            cell = new PdfPCell(new Paragraph("Total efectivo: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[8] != null ? "$" + res[8].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            efectivoCajaChica = new BigDecimal(res[8] == null ? "0.0" : res[8].toString());
            cell = new PdfPCell(new Paragraph("Total efectivo: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[14] != null ? "$" + res[14].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            efectivoCajaGral = new BigDecimal(res[14] == null ? "0.0" : res[14].toString());
            
            cell = new PdfPCell(new Paragraph("Total monedas: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[9] != null ? "$" + res[9].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            monedasCajaChica = new BigDecimal(res[9] == null ? "0.0" : res[9].toString());
            cell = new PdfPCell(new Paragraph("Total monedas: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[15] != null ? "$" + res[15].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            monedasCajaGral = new BigDecimal(res[15] == null ? "0.0" : res[15].toString());
            
            cell = new PdfPCell(new Paragraph("Diferencia: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            BigDecimal difCajaChica = sobresCajaChica.add(efectivoCajaChica).add(monedasCajaChica).subtract(totalCajaChica);
            cell = new PdfPCell(new Paragraph(difCajaChica != null ? "$" + difCajaChica.toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("Diferencia: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            BigDecimal difCajaGral = sobresCajaGral.add(efectivoCajaGral).add(monedasCajaGral).subtract(totalCajaGral);
            cell = new PdfPCell(new Paragraph(difCajaGral != null ? "$" + difCajaGral.toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            
            cell = new PdfPCell(new Paragraph("Comentarios: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[11] != null ? res[11].toString() : "",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("Comentarios: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(res[17] != null ? res[17].toString() : "",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(0);
            cell.setColspan(1);
            table.addCell(cell);

            document.add(table);
            document.add(Chunk.NEWLINE);
            
            PdfPTable tableRes = new PdfPTable(2);
            tableRes.setTotalWidth(new float[]{100f, 460f});

            tableRes.setLockedWidth(true);
            PdfPCell cellRes = new PdfPCell(new Paragraph("Resumen del día",
                    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("Cortes del día: ",
                    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[18] != null ? "$" + res[18].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("Subtotal: ",
                    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[19] != null ? "$" + res[19].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("Comisión ap.: ",
                    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[20] != null ? "$" + res[20].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("Cobranza: ",
                    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[21] != null ? "$" + res[21].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("Colocación: ",
                    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[22] != null ? "$" + res[22].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);
            
            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;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();
    }

}
