/*
 * 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.admin.ClosingDayController;
import com.arrebol.apc.controller.admin.LoanController;
import com.arrebol.apc.model.admin.ClosingDay;
import com.arrebol.apc.model.admin.ClosingDayDetail;
import com.arrebol.apc.model.catalog.RouteCtlg;
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.system.logs.Bitacora;
import com.arrebol.apc.model.views.ClosingDailyDetailFromUserByCurdateView;
import com.arrebol.apc.model.views.LoanByUserPaymentZeroView;
import com.arrebol.apc.model.views.TotalCashByCurdateDashboardView;
import com.arrebol.apc.model.views.TotalCashByCurdateView;
import com.arrebol.apc.model.views.TotalClosingDayByCurdateView;
import com.arrebol.apc.web.beans.Datatable;
import com.arrebol.apc.web.beans.GenericBean;
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.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 */
@Named("closingDayManager")
@ViewScoped
public class ClosingDayBean 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 {
                setClosingDay(getClosingDayCtrl().fillClosingDayDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate()));
            }
        } catch (Exception e) {
        }
    }

    public List<ClosingDay> fillDatatableClosingDay() {

        return getClosingDayCtrl().fillClosingDayDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate());
    }

    /**
     *
     * @param outcome
     * @return
     */
    public String detailClosingDay(String outcome) {
        return outcome;
    }

    public List<User> getUsers() {

        return genericCtrl.getAllUsersByOffice(getLoggedUser().getOffice().getId());
    }

    public List<ClosingDailyDetailFromUserByCurdateView> fillDatatableClosingDetails(String idUser) {

        return closingDayCtrl.findAllClosingDailyDetailFromUserByCurdateView(idUser);
    }

    public List<LoanByUserPaymentZeroView> getLoansPaymentZeroByUser(String idUser) {

        return closingDayCtrl.getLoansPaymentZeroByUser(idUser);
    }

    public void getResumen() {

        List<TotalCashByCurdateDashboardView> listTotal = closingDayCtrl.getAllTotalCashByCurdateDashboardView(getLoggedUser().getOffice().getId());
        totalAmount = BigDecimal.ZERO;
        totalTransferSender = BigDecimal.ZERO;
        totalTransferReceiver = BigDecimal.ZERO;
        totalMoneyDaily = BigDecimal.ZERO;
        totalDelivery = BigDecimal.ZERO;
        totalFinal = BigDecimal.ZERO;
        totalCaja = BigDecimal.ZERO;
        totalOtherExpense = BigDecimal.ZERO;
        deposit = BigDecimal.ZERO;

        for (TotalCashByCurdateDashboardView temp : listTotal) {
            totalAmount = totalAmount.add(temp.getPaymentDaily());
            totalTransferSender = totalTransferSender.add(temp.getTransferSender());
            totalTransferReceiver = totalTransferReceiver.add(temp.getTransferReceiver());
            totalMoneyDaily = totalMoneyDaily.add(temp.getMoneyDaily());
            totalDelivery = totalDelivery.add(temp.getDelivery());
            deposit = deposit.add(temp.getDepositDaily());
            totalFinal = totalFinal.add(temp.getTotal());
            totalOtherExpense = totalOtherExpense.add(temp.getOtherExpense());
        }

        List<TotalClosingDayByCurdateView> closingTotal = closingDayCtrl.findAllClosingDayByCurdate(getLoggedUser().getOffice().getId());
        if (closingTotal != null && !closingTotal.isEmpty()) {
            for (TotalClosingDayByCurdateView temp : closingTotal) {
                totalCaja = totalCaja.add(temp.getAmountPaid());
            }
        }

    }

    public void getCashTotal() {
        
        
        if(userId.equalsIgnoreCase("")){
            FacesMessage msg = new FacesMessage("ERROR", "Debes de elegir un usuario para poder ver sus totales");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            imprimirStatus = true;
            userId = "";
            return;
        }
        if(loanCtrl.countLoanDetailsAuthorize(userId)>0){
            FacesMessage msg = new FacesMessage("Depositos pendientes", "No se puede realizar el corte de caja, autorice todas los depositos pendientes");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            userId = "";
            return;
        }

        if (closingDayCtrl.getClosingDayCurdateByUserId(userId, getLoggedUser().getOffice().getId()) > 0) {
            FacesMessage msg = new FacesMessage("Corte encontrado", "El usuario ya tiene un corte registrado el día de hoy.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            userId = "";
            return;
        }
        totales = new TotalCashByCurdateView();
        totales.setMoneyDaily(BigDecimal.ZERO);
        totales.setPaymentDaily(BigDecimal.ZERO);
        totales.setTransferReceiver(BigDecimal.ZERO);
        totales.setTransferSender(BigDecimal.ZERO);
        totales.setDelivery(BigDecimal.ZERO);
        totales.setTransferPending(BigDecimal.ZERO);
        totales.setOtherExpense(BigDecimal.ZERO);
        totales.setDepositDaily(BigDecimal.ZERO);
        total = BigDecimal.ZERO.toString();
        totalCustomerWithOutAction = new Long(0);
        comments = "";
        TotalCashByCurdateView temp;
        temp = closingDayCtrl.getTotalCashByCurdateViewById(userId);
        if (temp != null) {
            totales = temp;
            total = temp.getTotal().toString();
        }

        if (closingDetail != null && !closingDetail.isEmpty()) {
            closingDetail.clear();
        }

        User userObj = closingDayCtrl.getUserById(userId);
        
       
        if (userObj.getCertifier().equals(ActiveStatus.DISABLED)) {
            closingDetail = fillDatatableClosingDetails(userId);
        } else {
            closingDetail = closingDayCtrl.findAllClosingDailyDetailFromUserCertifierByCurdateView(userId);
        }

        totalCustomerWithOutAction = closingDayCtrl.getLoansCountDailyByUser(userId);
        paymentoZeroDetail = getLoansPaymentZeroByUser(userId);
       
         imprimirStatus = false;
       // imprimirStatus();
    }
    
    public void imprimir() {
        if (userId.equalsIgnoreCase("")) {
            FacesMessage msg = new FacesMessage("ERROR", "Debes de elegir un usuario para poder imprimir el corte.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            userId = "";
            imprimirStatus = true;
            return;
        }
        Document document = new Document(PageSize.LETTER);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            PdfWriter.getInstance(document, baos);
            List<Object> results = new ArrayList<>();
            results = closingDayCtrl.findDetailsFromClosingDayCurDate(userId);
            document.open();

            DateFormat formatter = new SimpleDateFormat("dd/MM/yy");
            DateFormat formatter2 = new SimpleDateFormat("dd/MM/yyyy HH:mm:SS");
            formatter2.setTimeZone(TimeZone.getTimeZone("GMT-6"));

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

//            Image imagen = Image.getInstance("other sources/resources/serenity-layout/images/ace_logo.jpg");
//            imagen.scaleAbsoluteWidth(100f);
//            document.add(imagen);
            
            Paragraph title = new Paragraph("Corte del día", 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 totalesRep = BigDecimal.ZERO;
            BigDecimal recuperado = BigDecimal.ZERO;
            BigDecimal transEnv = BigDecimal.ZERO;
            BigDecimal transRec = BigDecimal.ZERO;
            BigDecimal inicio = BigDecimal.ZERO;
            BigDecimal gastos = BigDecimal.ZERO;
            BigDecimal depositos = BigDecimal.ZERO;
            BigDecimal entrPrestamos = BigDecimal.ZERO;
            
            
            PdfPTable tableGen = new PdfPTable(4);
            tableGen.setWidthPercentage(100);
            tableGen.setTotalWidth(new float[]{100f, 170f, 140f, 150f});
            tableGen.setLockedWidth(true);
            
            PdfPCell cellGen = new PdfPCell(new Paragraph("Asesor: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph(res[8] == null ? "" : res[8].toString(),
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(3);
            tableGen.addCell(cellGen);
            
            cellGen = new PdfPCell(new Paragraph("Monto recuperado: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            recuperado = new BigDecimal(res[9] == null ? "0.0" : res[9].toString());
            cellGen = new PdfPCell(new Paragraph(res[9] != null ? "$" + res[9].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Monto enviado por transferencia: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            transEnv = new BigDecimal(res[11] == null ? "0.0" : res[11].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[11] != null ? "$" + res[11].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            
            cellGen = new PdfPCell(new Paragraph("Monto de inicio: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            inicio = new BigDecimal(res[13] == null ? "0.0" : res[13].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[13] != null ? "$" + res[13].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Monto recibido por transferencia: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            transRec = new BigDecimal(res[12] == null ? "0.0" : res[12].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[12] != null ? "$" + res[12].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            
            cellGen = new PdfPCell(new Paragraph("Entrega de préstamos: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            entrPrestamos = new BigDecimal(res[15] == null ? "0.0" : res[15].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[15] != null ? "$" + res[15].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Gastos: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            gastos = new BigDecimal(res[14] == null ? "0.0" : res[14].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[14] != null ? "$" + res[14].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            
            cellGen = new PdfPCell(new Paragraph("Depósitos: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            depositos = new BigDecimal(res[10] == null ? "0.0" : res[10].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[10] != null ? "$" + res[10].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            totalesRep = totalesRep.add(recuperado).subtract(transEnv).add(transRec).add(inicio).subtract(gastos).subtract(entrPrestamos);
            cellGen = new PdfPCell(new Paragraph("Total: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph(totalesRep != null ? "$" + totalesRep.toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            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_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph(totales.getTotal() != null ? "$" + totales.getTotal().toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Monto Entregado: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph(new BigDecimal(total) != null ? "$" + new BigDecimal(total).toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            
            document.add(tableGen);
            document.add(Chunk.NEWLINE);
            
            PdfPTable table = new PdfPTable(7);
            table.setTotalWidth(new float[]{60, 60, 60, 60, 170, 60, 100});

            table.setLockedWidth(true);
            PdfPCell cell = new PdfPCell(new Paragraph("Detalles del corte",
                    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("Detalle",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

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

            cell = new PdfPCell(new Paragraph("C. apertura",
                    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",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

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

            cell = new PdfPCell(new Paragraph("Tipo",
                    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);

            for(Object result : results){
                Object[] tmp = (Object[]) result;
                // Detalle
                cell = new PdfPCell(new Paragraph(tmp[0] == null ? "" : tmp[0].toString(),
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                //Préstamo anterior
                cell = new PdfPCell(new Paragraph(tmp[6] != null ? "$" + tmp[6].toString() : "$0.00",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                // Comisión por apertura
                cell = new PdfPCell(new Paragraph(tmp[5] != null ? "$" + tmp[5].toString() : "$0.00",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                // Monto
                cell = new PdfPCell(new Paragraph(tmp[1] != null ? "$" + tmp[1].toString() : "$0.00",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                // Saldo insoluto
                cell = new PdfPCell(new Paragraph(tmp[3] != null ? "$" + tmp[3].toString() : "$0.00",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                // Tipo
                cell = new PdfPCell(new Paragraph(tmp[2] == null ? "" : tmp[2].toString(),
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                // Fecha
                cell = new PdfPCell(new Paragraph(tmp[4] == null ? "" : formatter2.format((Date) tmp[4]),
                        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.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.setHeader("Content-disposition",  "attachment;filename=corte_del_día.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();
        }
    }
    
    public void imprimirHistory() {
       
        Document document = new Document(PageSize.LETTER);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            PdfWriter.getInstance(document, baos);
            List<Object> results = new ArrayList<>();
            results = closingDayCtrl.findDetailsFromClosingDayHisotry(selectedClosingDay.getId());
            document.open();
            DateFormat formatter2 = new SimpleDateFormat("dd/MM/yyyy HH:mm:SS");
            formatter2.setTimeZone(TimeZone.getTimeZone("GMT-6"));

            Object[] res = (Object[]) results.get(0);
            BigDecimal totalesRep = BigDecimal.ZERO;
            BigDecimal recuperado = BigDecimal.ZERO;
            BigDecimal transEnv = BigDecimal.ZERO;
            BigDecimal transRec = BigDecimal.ZERO;
            BigDecimal inicio = BigDecimal.ZERO;
            BigDecimal gastos = BigDecimal.ZERO;
            BigDecimal depositos = BigDecimal.ZERO;
            BigDecimal entrPrestamos = BigDecimal.ZERO;
            
            Paragraph printDate = new Paragraph("Fecha de impresión: " +res[3], FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.DARK_GRAY));
            printDate.setAlignment(Element.ALIGN_RIGHT);
            document.add(printDate);

//            Image imagen = Image.getInstance("other sources/resources/serenity-layout/images/apc_card.png");
//            imagen.scaleAbsoluteWidth(100f);
//            document.add(imagen);
            
            Paragraph title = new Paragraph("Corte del día", FontFactory.getFont("arial", 18, Font.BOLD, BaseColor.DARK_GRAY));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);            
            
            document.add(Chunk.NEWLINE);
            
            
            
            
            PdfPTable tableGen = new PdfPTable(4);
            tableGen.setWidthPercentage(100);
            tableGen.setTotalWidth(new float[]{100f, 170f, 140f, 150f});
            tableGen.setLockedWidth(true);
            
            PdfPCell cellGen = new PdfPCell(new Paragraph("Asesor: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph(res[6] == null ? "" : res[6].toString(),
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(3);
            tableGen.addCell(cellGen);
            
            cellGen = new PdfPCell(new Paragraph("Monto recuperado: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            recuperado = new BigDecimal(res[7] == null ? "0.0" : res[7].toString());
            cellGen = new PdfPCell(new Paragraph(res[7] != null ? "$" + res[7].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Monto enviado por transferencia: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            transEnv = new BigDecimal(res[11] == null ? "0.0" : res[11].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[11] != null ? "$" + res[11].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            
            cellGen = new PdfPCell(new Paragraph("Monto de inicio: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            inicio = new BigDecimal(res[10] == null ? "0.0" : res[10].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[10] != null ? "$" + res[10].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Monto recibido por transferencia: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            transRec = new BigDecimal(res[11] == null ? "0.0" : res[11].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[11] != null ? "$" + res[11].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            
            cellGen = new PdfPCell(new Paragraph("Entrega de préstamos: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            entrPrestamos = new BigDecimal(res[13] == null ? "0.0" : res[13].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[13] != null ? "$" + res[13].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Gastos: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            gastos = new BigDecimal(res[12] == null ? "0.0" : res[12].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[12] != null ? "$" + res[12].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            
            cellGen = new PdfPCell(new Paragraph("Depósitos: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            depositos = new BigDecimal(res[8] == null ? "0.0" : res[8].toString()); 
            cellGen = new PdfPCell(new Paragraph(res[8] != null ? "$" + res[8].toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            totalesRep = totalesRep.add(recuperado).subtract(transEnv).add(transRec).add(inicio).subtract(gastos).subtract(entrPrestamos);
            cellGen = new PdfPCell(new Paragraph("Total: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph(totalesRep != null ? "$" + totalesRep.toString() : "$0.00",
                    FontFactory.getFont("arial", 8, Font.PLAIN, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            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_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            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_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            cellGen = new PdfPCell(new Paragraph("Monto Entregado: ",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cellGen.setHorizontalAlignment(Element.ALIGN_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            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_LEFT);
            cellGen.setBorder(0);
            cellGen.setColspan(1);
            tableGen.addCell(cellGen);
            
            document.add(tableGen);
            document.add(Chunk.NEWLINE);
            
            PdfPTable table = new PdfPTable(7);
            table.setTotalWidth(new float[]{60, 60, 60, 60, 170, 60, 100});

            table.setLockedWidth(true);
            PdfPCell cell = new PdfPCell(new Paragraph("Detalles del corte",
                    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("Detalle",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

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

            cell = new PdfPCell(new Paragraph("C. apertura",
                    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",
                    FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            table.addCell(cell);

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

            cell = new PdfPCell(new Paragraph("Tipo",
                    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);

            for(Object result : results){
                Object[] tmp = (Object[]) result;
                // Detalle
                cell = new PdfPCell(new Paragraph(tmp[0] == null ? "" : tmp[0].toString(),
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
               cell = new PdfPCell(new Paragraph( "",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                 cell = new PdfPCell(new Paragraph( "",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                
                
                // Monto
                cell = new PdfPCell(new Paragraph(tmp[1] != null ? "$" + tmp[1].toString() : "$0.00",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                
                 cell = new PdfPCell(new Paragraph( "",
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                
                // Tipo
                cell = new PdfPCell(new Paragraph(tmp[2] == null ? "" : tmp[2].toString(),
                        FontFactory.getFont("arial", 6, Font.PLAIN, BaseColor.BLACK)));
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setColspan(1);
                table.addCell(cell);
                // Fecha
                cell = new PdfPCell(new Paragraph(tmp[15] == null ? "" : formatter2.format((Date) tmp[15]),
                        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.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[6] == null ? "" : res[6].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.setHeader("Content-disposition",  "attachment;filename=corte_del_día.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();
        }
    }

    @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 (userId.equalsIgnoreCase("")) {
            FacesMessage msg = new FacesMessage("ERROR", "Debes de elegir un usuario para poder generar el corte.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            imprimirStatus = true;
            userId = "";
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 12);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

        if (!(dayOfWeek == Calendar.SUNDAY) && !(userId.equalsIgnoreCase("aad0c673-eb93-11ea-b7e1-02907d0fb4e6"))) {
            if (totalCustomerWithOutAction.compareTo(new Long(0)) == 1) {
                FacesMessage msg = new FacesMessage("ERROR", "El asesor debe de realizar una acción en todos sus préstamos.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return;
            }
        }
        
        if (totales.getTotal().compareTo(new BigDecimal(total)) != 0) {
            if (comments == null || comments.trim().equals("")) {
                FacesMessage msg = new FacesMessage("ERROR", "Es necesario capturar las observaciones.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return;
            }
        }

        User userData = null;
        for(User us : user){
            if(us.getId().equalsIgnoreCase(userId)){
                userData = us;
                break;
            }
        }

        ClosingDay closingSave = new ClosingDay();
        closingSave.setActiveStatus(ActiveStatus.ENEBLED);
        closingSave.setAmountExpected(totales.getTotal());
        closingSave.setAmountPaid(new BigDecimal(total));
        closingSave.setOffice(new Office(getLoggedUser().getOffice().getId()));
        closingSave.setUser(new User(userId));
        closingSave.setCreatedBy(getLoggedUser().getId());
        closingSave.setCreatedOn(new Date());
        closingSave.setComments(comments);
        closingSave.setRouteCtlg(userData.getHumanResource().getHumanResourceHasRoutes().get(0).getRouteCtlg());
        if (closingDayCtrl.saveClosingDay(closingSave)) {
            if (closingDetail != null && !closingDetail.isEmpty()) {
                List<ClosingDayDetail> detail = new ArrayList<ClosingDayDetail>();

                for (ClosingDailyDetailFromUserByCurdateView info : closingDetail) {
                    ClosingDayDetail detailInfo = new ClosingDayDetail();
                    detailInfo.setAmount(info.getAmount());
                    detailInfo.setClosingDay(closingSave);
                    detailInfo.setComments(info.getComments());
                    detailInfo.setCreatedBy(getLoggedUser().getId());
                    detailInfo.setCreatedOn(new Date());
                    detailInfo.setDateDetail(info.getCreatedOn());
                    detailInfo.setType(info.getType());
                    detail.add(detailInfo);
                }
                closingDayCtrl.saveClosingDayDetail(detail);
            }

        }
        getResumen();
        totales = new TotalCashByCurdateView();
        totales.setMoneyDaily(BigDecimal.ZERO);
        totales.setPaymentDaily(BigDecimal.ZERO);
        totales.setTransferReceiver(BigDecimal.ZERO);
        totales.setTransferSender(BigDecimal.ZERO);
        totales.setDelivery(BigDecimal.ZERO);
        totales.setTotal(BigDecimal.ZERO);
        totales.setTransferPending(BigDecimal.ZERO);
        totales.setOtherExpense(BigDecimal.ZERO);
        totales.setDepositDaily(BigDecimal.ZERO);
        total = BigDecimal.ZERO.toString();
        totalBox = BigDecimal.ZERO;
        totalCustomerWithOutAction = new Long(0);
        totalBox = genericCtrl.findAllSmallBox(getLoggedUser().getOffice().getId());
        comments = "";
        closingDetail.clear();
        paymentoZeroDetail.clear();
        FacesMessage msg = new FacesMessage("Nuevo corte registrado", "Se agregó correctamente");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    @Override
    public void deleteRow() {
        try {
            if (closingDayCtrl.existStableSmallBoxByCreatedOn(selectedClosingDay.getCreatedOn())) {
                showMessage(FacesMessage.SEVERITY_WARN, "Corte del día", "No se puede borrar porque ya se realizo el cuadre de caja chica del día.");
            } else {
                boolean delete = true;
                delete = selectedClosingDay.getActiveStatus() == ActiveStatus.ENEBLED ? true : false;

                if (delete) {
                    Bitacora bitacora = new Bitacora();
                    ClosingDay closing = closingDayCtrl.getClosingDayById(selectedClosingDay.getId());
                    bitacora.setAction("Eliminar corte del día");
                    bitacora.setCommentsUser(commentsBitacora);
                    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 del asesor " + closing.getUser().getUserName() + " con monto $"
                            + selectedClosingDay.getAmountPaid() + " y fecha " + closing.getCreatedOn());
                    closingDayCtrl.updateClosingDayByStatus(ActiveStatus.DISABLED, selectedClosingDay.getId(), getLoggedUser().getUser().getId());
                    //closingDay.remove(selectedClosingDay);
                    searchHistoricalAction();
                    bitacoraCtrl.saveBitacora(bitacora);
                    commentsBitacora = "";
                    selectedClosingDay = null;
                    showMessage(FacesMessage.SEVERITY_INFO, "Corte del día", "Se eliminó correctamente.");
                }
            }
        } catch (Exception e) {
        }
    }

    public ClosingDayController getClosingDayCtrl() {
        return closingDayCtrl;
    }

    public void setClosingDayCtrl(ClosingDayController closingDayCtrl) {
        this.closingDayCtrl = closingDayCtrl;
    }

    public List<ClosingDay> getClosingDay() {
        return closingDay;
    }

    public void setClosingDay(List<ClosingDay> closingDay) {
        this.closingDay = closingDay;
    }

    public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getAmount() {
        return amount;
    }

    public void setAmount(String amount) {
        this.amount = amount;
    }

    public ClosingDay getSelectedClosingDay() {
        return selectedClosingDay;
    }

    public void setSelectedClosingDay(ClosingDay selectedClosingDay) {
        this.selectedClosingDay = selectedClosingDay;
    }

    public TotalCashByCurdateView getTotales() {
        return totales;
    }

    public void setTotales(TotalCashByCurdateView totales) {
        this.totales = totales;
    }

    public String getTotal() {
        return total;
    }

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

    public BigDecimal getTotalAmount() {
        return totalAmount;
    }

    public void setTotalAmount(BigDecimal totalAmount) {
        this.totalAmount = totalAmount;
    }

    public BigDecimal getTotalTransferSender() {
        return totalTransferSender;
    }

    public void setTotalTransferSender(BigDecimal totalTransferSender) {
        this.totalTransferSender = totalTransferSender;
    }

    public BigDecimal getTotalTransferReceiver() {
        return totalTransferReceiver;
    }

    public void setTotalTransferReceiver(BigDecimal totalTransferReceiver) {
        this.totalTransferReceiver = totalTransferReceiver;
    }

    public BigDecimal getTotalMoneyDaily() {
        return totalMoneyDaily;
    }

    public void setTotalMoneyDaily(BigDecimal totalMoneyDaily) {
        this.totalMoneyDaily = totalMoneyDaily;
    }

    public BigDecimal getTotalDelivery() {
        return totalDelivery;
    }

    public void setTotalDelivery(BigDecimal totalDelivery) {
        this.totalDelivery = totalDelivery;
    }

    public BigDecimal getTotalFinal() {
        return totalFinal;
    }

    public void setTotalFinal(BigDecimal totalFinal) {
        this.totalFinal = totalFinal;
    }

    public BigDecimal getTotalCaja() {
        return totalCaja;
    }

    public void setTotalCaja(BigDecimal totalCaja) {
        this.totalCaja = totalCaja;
    }

    public BigDecimal getTotalOtherExpense() {
        return totalOtherExpense;
    }

    public void setTotalOtherExpense(BigDecimal totalOtherExpense) {
        this.totalOtherExpense = totalOtherExpense;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public GenericController getGenericCtrl() {
        return genericCtrl;
    }

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

    public List<ClosingDailyDetailFromUserByCurdateView> getClosingDetail() {
        return closingDetail;
    }

    public void setClosingDetail(List<ClosingDailyDetailFromUserByCurdateView> closingDetail) {
        this.closingDetail = closingDetail;
    }

    public BigDecimal getTotalBox() {
        return totalBox;
    }

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

    public Long getTotalCustomerWithOutAction() {
        return totalCustomerWithOutAction;
    }

    public void setTotalCustomerWithOutAction(Long totalCustomerWithOutAction) {
        this.totalCustomerWithOutAction = totalCustomerWithOutAction;
    }

    public List<LoanByUserPaymentZeroView> getPaymentoZeroDetail() {
        return paymentoZeroDetail;
    }

    public void setPaymentoZeroDetail(List<LoanByUserPaymentZeroView> paymentoZeroDetail) {
        this.paymentoZeroDetail = paymentoZeroDetail;
    }

    public BigDecimal getDeposit() {
        return deposit;
    }

    public void setDeposit(BigDecimal deposit) {
        this.deposit = deposit;
    }

    public String getCommentsBitacora() {
        return commentsBitacora;
    }

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

    public LoanController getLoanCtrl() {
        return loanCtrl;
    }

    public void setLoanCtrl(LoanController loanCtrl) {
        this.loanCtrl = loanCtrl;
    }

    public boolean getImprimirStatus() {
        return imprimirStatus;
    }

    public void setImprimirStatus(boolean imprimirStatus) {
        this.imprimirStatus = imprimirStatus;
    }

   
    
    private ClosingDayController closingDayCtrl;
    private GenericController genericCtrl;
    private BitacoraController bitacoraCtrl;
    private LoanController loanCtrl;

    private List<ClosingDay> closingDay;
    private List<User> user;

    private String userId;
    private String amount;
    private String total;

    private BigDecimal totalAmount;
    private BigDecimal totalTransferSender;
    private BigDecimal totalTransferReceiver;
    private BigDecimal totalMoneyDaily;
    private BigDecimal totalDelivery;
    private BigDecimal totalFinal;
    private BigDecimal totalCaja;
    private BigDecimal totalOtherExpense;
    private BigDecimal totalBox;
    private Long totalCustomerWithOutAction;
    private BigDecimal deposit;

    private String commentsBitacora;

    private String comments;
    private boolean imprimirStatus;

    private TotalCashByCurdateView totales;

    private ClosingDay selectedClosingDay;

    private List<ClosingDailyDetailFromUserByCurdateView> closingDetail;
    private List<LoanByUserPaymentZeroView> paymentoZeroDetail;

    @PostConstruct
    public void init() {
        loadBundlePropertyFile();
        
        loanCtrl = new LoanController();
        closingDayCtrl = new ClosingDayController();
        bitacoraCtrl = new BitacoraController();
        genericCtrl = new GenericController();

        //initOneWeekBeforeToCurrdate();
        initThisWeekToCurrdate();

        imprimirStatus = true;
        closingDay = fillDatatableClosingDay();
        commentsBitacora = "";
        user = getUsers();
        getResumen();
        comments = "";
        totalBox = genericCtrl.findAllSmallBox(getLoggedUser().getOffice().getId());
    }

}
