package trigger_package;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import main_package.DataBaseMethods;
import main_package.DataBaseConnection;
import main_package.DataBaseMethodTaheer;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import report_package.DataBaseReportMethods;

// This class generate Daily Collection Report Of the account of Loan, DD, RD, FD Head and calculate cash and 
// bank Collection amount of the current Day.

public class SchedulerJob implements Job 
{   
	public void execute(JobExecutionContext context)throws JobExecutionException
    {   
        System.out.println("shedular job run");    	
    	Connection con = DataBaseConnection.JAVAConnection(); 
    	List<Integer> branchList = new ArrayList<Integer>();
    	branchList = new DataBaseMethods().branchListAll(con);
    	DataBaseMethodTaheer dbmt = new DataBaseMethodTaheer();
    	
    	for(int i=0;i<branchList.size();i++)
	   {
	    	int branchId = branchList.get(i);
	    	
	    	DataBaseReportMethods dbm = new DataBaseReportMethods();
	    	DataBaseMethods db = new DataBaseMethods();
	    	DecimalFormat df = new DecimalFormat("##.##");
	    	Connection conn = DataBaseConnection.JAVAConnection();
	    	String msgStatus = db.checkMessageApiStatus(conn);

	    	if(msgStatus.equalsIgnoreCase("active"))
			{
				Date startDate=new Date();
				try {
					startDate = new SimpleDateFormat("dd-MM-yyyy").parse("25-06-2026");
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    	Date endDate=new Date();
		    	double loanAmount,rdAmount,fdAmount,totalAmount, ddAmount;
		    	
		    	loanAmount=dbm.dailyEmiCollectionBetweenDate(branchId,startDate, endDate, "both", "both",conn, "");
				ddAmount=dbm.dailyRdFdCollectionBetweenDate(branchId,startDate, endDate, "both", "DD",conn, "");
				rdAmount=dbm.dailyRdFdCollectionBetweenDate(branchId,startDate, endDate, "both", "RD",conn, "");
				fdAmount=dbm.dailyRdFdCollectionBetweenDate(branchId,startDate, endDate, "both", "FD",conn, "");
				
				totalAmount=loanAmount+ddAmount+rdAmount+fdAmount;
				totalAmount=Double.parseDouble(df.format(totalAmount));
				
				String dt=new SimpleDateFormat("dd-MMM-yyyy").format(startDate);
				
				String typeMessage="System Generated Collection Report Of "+dt +" is: Loan Rs. "+loanAmount+", DD Rs. "+ddAmount+", RD Rs. "+rdAmount+", FD Rs. "+fdAmount+" And Total Collection Rs. "+totalAmount+" Thanks.";
				
				double cashBalance=db.remainingCompanyCapitalAmount(branchId,conn);
				cashBalance=Double.parseDouble(df.format(cashBalance));
				String cashMsg="System Generated Cash Report Of "+dt +" is Rs. "+cashBalance+ "/- Thanks.";
				cashBalance=Double.parseDouble(df.format(cashBalance));
				
				if (totalAmount > 0) 
				{
					String contactNo = db.contactNoForSchedularMsg(branchId, conn);

					boolean isDLT = dbmt.isDLTMessageApi(conn);
				    
					if (isDLT) 
				    {
						Map<String, String> variables = new HashMap<>();

						variables.put("date", dt);
						variables.put("loan", String.valueOf(loanAmount));
						variables.put("dd", String.valueOf(ddAmount));
						variables.put("rd", String.valueOf(rdAmount));
						variables.put("fd", String.valueOf(fdAmount));
						variables.put("total", String.valueOf(totalAmount));
						variables.put("cash", String.valueOf(cashBalance));
						
				    	for (int z = 0; z < 3; z++)
				    	{
				    		dbmt.sendDLTMessage(contactNo, null, variables, conn, "cash report");
				    	}

				    	String contactNo2 = db.contactNoForSchedularMsgForOtherDirectors(branchId,"mobile_no_two",conn);

				    	if(contactNo2 != null && !contactNo2.trim().equalsIgnoreCase("") && contactNo2.length() == 10)
				    	{
				    		dbmt.sendDLTMessage(contactNo2, null, variables,conn,"cash report");
				    	}

				    	String contactNo3 = db.contactNoForSchedularMsgForOtherDirectors( branchId, "mobile_no_three", conn);

				    	if(contactNo3 != null && !contactNo3.trim().equalsIgnoreCase("") && contactNo3.length() == 10)
				    	{
				    		dbmt.sendDLTMessage(contactNo3, null,variables,conn,"cash report");
				    	} 
				    } 
					else
					{
			          db.runMessageUrl(branchId,contactNo,typeMessage, "System", "1207166054337690080",conn);
			          db.runMessageUrl(branchId,contactNo,cashMsg,"System","1207166054324020000",conn );

			          String contactNo2 = db.contactNoForSchedularMsgForOtherDirectors(branchId,"mobile_no_two",conn);
			          if(contactNo2 != null && !contactNo2.trim().equalsIgnoreCase("") && contactNo2.length() == 10)
			          {
			              db.runMessageUrl(branchId,contactNo2,typeMessage,"System","1207166054337690080",conn);
			              db.runMessageUrl( branchId, contactNo2, cashMsg, "System", "1207166054324020000", conn);
			          }


			          String contactNo3 = db.contactNoForSchedularMsgForOtherDirectors( branchId, "mobile_no_three", conn);
			          if(contactNo3 != null&& !contactNo3.trim().equalsIgnoreCase("")&& contactNo3.length() == 10)
			          {
			              db.runMessageUrl(branchId,contactNo3,typeMessage,"System","1207166054337690080",conn);
			              db.runMessageUrl(branchId,contactNo3,cashMsg, "System", "1207166054324020000", conn);
			          }
					}
				}	
			}
			
			
			// Employee Auto Logout Code
			String companyName = dbmt.companyNameByBranchId(branchId); 
			if (!"SUDERSHANA FINANCE".equalsIgnoreCase(companyName) || !"".equalsIgnoreCase(companyName) ) 
			{   
				
				String edt=String.valueOf(new Timestamp(new Date().getTime()));
				String logDt=edt.substring(0, 10);
				String logTm=edt.substring(11, 19);
                db.updateInAttendanceTable(branchId,"all", logDt, logTm, "0.00", "0.00", "System", conn, "");				    
				//db.autoLogoutAllPendingAttendance(branchId, logDt, logTm, "0.00", "0.00", "System", conn);
			    
			} 				
			
			///////////////////////////////// Delete old Data From Query Table
			db.deleteQueryTableOldData(conn);
	        
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
    }
}