/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arrebol.apc.controller.drive;

import com.arrebol.apc.controller.util.ConnectionManager;
import com.arrebol.apc.controller.util.HibernateUtil;
import com.arrebol.apc.model.views.FaltanteInDates;
//import com.arrebol.apc.repository.GenericEntityRepository;
import java.io.Serializable;
import java.math.BigDecimal;
//import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;


/**
 *
 * @author Donadony
 */
public class FaltanteInDatesController extends ConnectionManager implements Serializable {
    
    
    public List<FaltanteInDates> getAllLoanWeekMySQLQuery(String startDate,String endDate) {
        logger.debug("getAllLoanWeekByOfficeMySQLQuery");
        logger.debug("Fecha inicial: " + startDate);

        List<FaltanteInDates> dataList = new ArrayList<>();
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            //SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

            List<Object> rows = session.createNativeQuery(queryLoan)
                    .setParameter("startDate", startDate)
                    .setParameter("endDate",endDate)
                    .getResultList();
            
            transaction.commit();
            
            rows.forEach((row) -> {
                Object[] results = (Object[]) row;

                // Create Data Row
                FaltanteInDates loanWeek = new FaltanteInDates( );
                loanWeek.setId(results[0] == null ? "" : results[0].toString());
                loanWeek.setIdUser(results[1] == null ? "" : results[1].toString());
                loanWeek.setUserName(results[2] == null ? "" : results[2].toString());
                loanWeek.setCustomerName(results[3] == null ? "" : results[3].toString());
                loanWeek.setRouteName(results[4] == null ? "" : results[4].toString());
                loanWeek.setAmountPaid(new BigDecimal(results[5] == null ? "0.0" : results[5].toString()));
                loanWeek.setAmountToPay(new BigDecimal(results[6] == null ? "0.0" : results[6].toString()));
                loanWeek.setAmountToPayNoFee(new BigDecimal(results[7] == null ? "0.0" : results[7].toString()));
                loanWeek.setPaymentDaily(new BigDecimal(results[8] == null ? "0.0" : results[8].toString()));
                loanWeek.setExpectedPayment(new BigDecimal(results[9] == null ? "0.0" : results[9].toString()));
                loanWeek.setAmountPaidDetails(new BigDecimal(results[10] == null ? "0.0" : results[10].toString()));
                loanWeek.setFee(new BigDecimal(results[11] == null ? "0.0" : results[11].toString()));
                loanWeek.setFeeNumber(results[12] == null ? 0 : (Long) results[12]);
                loanWeek.setNumPagosAll(results[13] == null ? 0 :(Long) results[13]);
                
                
                dataList.add(loanWeek);
            });
            
        } catch (HibernateException e) {
            logger.error("Driver", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getAllLoanWeekByOfficeMySQLQuery(" + startDate + " " + ") ", e);
            rollback(transaction);
        }
        
        return dataList;
    }
    
    final Logger logger = LogManager.getLogger(DriverController.class);
    /*private final GenericEntityRepository genericEntityRepository;
    
    public FaltanteInDatesController() {
        this.genericEntityRepository = new GenericEntityRepository();
    }*/
    
    
    private final String queryLoan = 
"SELECT " +
"	al.id," +
"    ald.id_user," +
"    CONCAT((CASE" +
"                    WHEN" +
"                        ((hr.first_name IS NOT NULL)" +
"                            AND (hr.first_name <> ''))" +
"                    THEN" +
"                        CONCAT(SUBSTR(UPPER(hr.first_name), 1, 1)," +
"                                SUBSTR(LOWER(hr.first_name), 2)," +
"                                ' ')" +
"                    ELSE ''" +
"                END)," +
"                (CASE" +
"                    WHEN" +
"                        ((hr.second_name IS NOT NULL)" +
"                            AND (hr.second_name <> ''))" +
"                    THEN" +
"                        CONCAT(SUBSTR(UPPER(hr.second_name), 1, 1)," +
"                                SUBSTR(LOWER(hr.second_name), 2)," +
"                                ' ')" +
"                    ELSE ''" +
"                END)," +
"                (CASE" +
"                    WHEN" +
"                        ((hr.last_name IS NOT NULL)" +
"                            AND (hr.last_name <> ''))" +
"                    THEN" +
"                        CONCAT(SUBSTR(UPPER(hr.last_name), 1, 1)," +
"                                SUBSTR(LOWER(hr.last_name), 2))" +
"                    ELSE ''" +
"                END)) AS user_name," +
"	 CONCAT((CASE" +
"                    WHEN" +
"                        ((cstmr.first_name IS NOT NULL)" +
"                            AND (cstmr.first_name <> ''))" +
"                    THEN" +
"                        CONCAT(SUBSTR(UPPER(cstmr.first_name)," +
"                                    1," +
"                                    1)," +
"                                SUBSTR(LOWER(cstmr.first_name), 2)," +
"                                ' ')" +
"                    ELSE ''" +
"                END)," +
"                (CASE" +
"                    WHEN" +
"                        ((cstmr.second_name IS NOT NULL)" +
"                            AND (cstmr.second_name <> ''))" +
"                    THEN\n" +
"                        CONCAT(SUBSTR(UPPER(cstmr.second_name)," +
"                                    1," +
"                                    1)," +
"                                SUBSTR(LOWER(cstmr.second_name), 2)," +
"                                ' ')" +
"                    ELSE ''" +
"                END)," +
"                (CASE" +
"                    WHEN" +
"                        ((cstmr.last_name IS NOT NULL)" +
"                            AND (cstmr.last_name <> ''))" +
"                    THEN" +
"                        CONCAT(SUBSTR(UPPER(cstmr.last_name), 1, 1)," +
"                                SUBSTR(LOWER(cstmr.last_name), 2))" +
"                    ELSE ''" +
"                END)) AS customer_name," +
"    ar.route_name," +
"    al.amount_paid," +
"    al.amount_to_pay, " +
"    al.amount_to_pay-(SELECT " +
"                IF((SUM(ldLunes.payment_amount) IS NULL)," +
"                        0," +
"                        SUM(ldLunes.payment_amount))" +
"            FROM" +
"                APC_LOAN_DETAIL ldLunes" +
"            WHERE" +
"                ((ldLunes.id_loan = al.id)" +
"                    AND (ldLunes.loan_details_type = 'FEE'))) AS amount_to_pay_no_fee," +
"    alt.payment_daily," +
"    (SELECT " +
"                COUNT(DISTINCT CAST(ldfaltante.created_on AS DATE))" +
"            FROM\n" +
"                APC_LOAN_DETAIL ldfaltante" +
"            WHERE" +
"                ((ldfaltante.id_loan = ald.id_loan)" +
"                AND ldfaltante.id_user = ald.id_user" +
"                    AND (LOWER(DAYNAME(CAST(ldfaltante.created_on AS DATE))) <> 'sunday')" +
"                    AND date(ldfaltante.created_on) >= :startDate and date(ldfaltante.created_on) <= :endDate" +
"                    AND (ldfaltante.loan_details_type = 'PAYMENT')))*alt.payment_daily as expected_payment," +
"    sum(ald.payment_amount) as amount_paid_details, " +
"    (SELECT " +
"                IF((SUM(ldLunes.payment_amount) IS NULL)," +
"                        0," +
"                        SUM(ldLunes.payment_amount))" +
"            FROM" +
"                APC_LOAN_DETAIL ldLunes" +
"            WHERE" +
"                ((ldLunes.id_loan = al.id)" +
"                    AND (ldLunes.loan_details_type = 'FEE'))) AS fee," +
"	(SELECT " +
"                count(ldLunes.created_on)" +
"            FROM" +
"                APC_LOAN_DETAIL ldLunes" +
"            WHERE\n" +
"                ((ldLunes.id_loan = al.id)" +
"                    AND (ldLunes.loan_details_type = 'FEE'))) AS fee_number," +
"    (SELECT " +
"                COUNT(DISTINCT CAST(ldfaltante.created_on AS DATE))" +
"            FROM\n" +
"                APC_LOAN_DETAIL ldfaltante" +
"            WHERE" +
"                ((ldfaltante.id_loan = ald.id_loan)" +
"                AND ldfaltante.id_user = ald.id_user" +
"                    AND (LOWER(DAYNAME(CAST(ldfaltante.created_on AS DATE))) <> 'sunday')" +
"                    AND date(ldfaltante.created_on) >= :startDate and date(ldfaltante.created_on) <= :endDate" +
"                    AND (ldfaltante.loan_details_type IN  ('PAYMENT','TRANSFER')))) AS num_pagos_all," + 
"    al.created_on " +
"FROM APC_LOAN_DETAIL ald" +
"JOIN APC_LOAN al ON al.id = ald.id_loan" +
"JOIN APC_USER au ON au.id = ald.id_user" +
"JOIN APC_ROUTE ar on al.id_route = ar.id" +
"JOIN APC_LOAN_BY_USER lub ON lub.id_loan = al.id" +
"JOIN APC_LOAN_TYPE alt on alt.id = al.id_loan_type" +
"JOIN APC_PEOPLE cstmr ON ((al.id_customer = cstmr.id))" +
"JOIN APC_USER u ON ((ald.id_user = u.id))" +
"JOIN APC_HUMAN_RESOURCE hr ON ((hr.id = u.id_human_resource))" +
"WHERE al.loan_status= 'APPROVED' AND ald.loan_details_type in('PAYMENT','TRANSFER') and date(ald.created_on) >= :startDate and date(ald.created_on) <= :endDate" +
" AND lub.id_user <> 'aad0c673-eb93-11ea-b7e1-02907d0fb4e6'" +
"group by ald.id_loan,ald.id_user";
}
