package hrm_package;

import java.io.Serializable;
import java.security.Timestamp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;

import org.apache.commons.net.ntp.TimeStamp;

import main_package.DataBaseConnection;
import main_package.DataBaseMethodRahul;
import main_package.DataBaseMethods;
import main_package.EmpInfo;

@ManagedBean(name="attendanceReport2")
@ViewScoped


public class AttendanceReportBean2 implements Serializable
{
	private static final long serialVersionUID = 1L;
	
	
	String empUserId;
	
	int branchId;
	int branchIds;
	private String selectedSelfie;
	Date startDate , endDate ;
	
	boolean show;
	
	ArrayList<EmpInfo> empAttendanceList, attendnceReportList;
	
	private ArrayList<EmpInfo> employees;
    
	private ArrayList<String> daysOfMonth, dateList;
	
	ArrayList<SelectItem> empList;
	DataBaseMethods dbm = new DataBaseMethods();
	DataBaseMethodRahul dbr = new DataBaseMethodRahul();
	
	String onlineFileViewPath;
	
			private String imagePath;
				SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); 
    
    ArrayList<SelectItem> empSe ; 
    ArrayList<EmpInfo> list=new ArrayList<>();
   
	
	public AttendanceReportBean2() 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	    branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		empList = dbm.employeeTypeList(branchId,conn);
		
		Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        startDate = cal.getTime();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        endDate = cal.getTime();
        empSe = new ArrayList<>();
          dbr.employeeNameAndUserId(empSe,branchId);

	}
	
	public void searchAttendanceReport() 
	{
	    attendnceReportList = new ArrayList<>();
	    dateList = new ArrayList<>();
	    
	    Calendar cal = Calendar.getInstance();
	    cal.setTime(startDate); 
	    
	    while (!cal.getTime().after(endDate)) 
	    {
	        dateList.add(sdf.format(cal.getTime()));
	        cal.add(Calendar.DATE, 1);
	    }
        
	    employeeDataList(branchIds);
	}
    
    
                                    
	public void employeeDataList(int branchIds) 
	{
		
	    if (startDate == null || endDate == null) return;
        
	    try (Connection conn = DataBaseConnection.JAVAConnection())
	    {
	        String query ;
	        
	        if (branchIds != -1) 
	        {
	            query = "SELECT * FROM employee WHERE branch_id = ? ";
	        } 
	        else 
	        {
	            query = "SELECT * FROM employee";
	        }
	        
	       
	        
	        try (PreparedStatement ps = conn.prepareStatement(query)) 
	        {
	        	if (branchIds != -1)
	        	{
	                ps.setInt(1, branchIds);
	            }
	            ResultSet rs = ps.executeQuery();
	            while (rs.next()) {
	                EmpInfo ei = new EmpInfo();

	                ei.setName(rs.getString("name"));
	                ei.setUname(rs.getString("uname"));
	                ei.setFname(rs.getString("fname"));
	                ei.setDob(rs.getDate("dob"));
	                ei.setStrDob(sdf.format(rs.getDate("dob")));
	                ei.setStrDoj(sdf.format(rs.getDate("doj")));
	                ei.setDsaCode(rs.getString("dsacode"));
	                ei.setDesignation(designationAndDepartmentNameByDesignationId(rs.getString("designation")));
	                ei.setDepartment(designationAndDepartmentNameByDesignationId(rs.getString("department")));
                                                                                                                                                                                                                                                                        
	                Map<String, String> attMap = new HashMap<>();
	                for (String d : dateList) 
	                {
	                    // parse using dd-MM-yyyy
	                    Date currentDate = sdf.parse(d);

	                    // convert to DB format yyyy-MM-dd
	                    String dbDateStr = sdf1.format(currentDate);

	                    boolean present = checkEmpAttendanceOfCurrentDate(ei.getUname(), dbDateStr);

	                    Calendar calDate = Calendar.getInstance();
	                    calDate.setTime(currentDate);

	                    String status;
	                    if (present) {
	                        status = "P"; // present
	                    } else if (calDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
	                        status = "H"; // holiday
	                    } else {
	                        status = "A"; // absent
	                    }

	                    attMap.put(d, status);
	                }

	                ei.setAttendanceMap(attMap);


	                int present = (int) attMap.values().stream().filter(s -> s.equals("P")).count();
	                int holidays = (int) attMap.values().stream().filter(s -> s.equals("H")).count();
	                int totalWorking = present + holidays;
	                int totalAbsent = (int) attMap.values().stream().filter(s -> s.equals("A")).count();
	               

	                ei.setTotalPresent(present);
	                ei.setTotalAbsent(totalAbsent);
	                ei.setTotalHoliday(holidays);
	                ei.setTotalWorking(totalWorking);

	                attendnceReportList.add(ei);
	            }
	        }
	    } 
	    catch (Exception e) 
	    {
	        e.printStackTrace();
	    }
	}
	
	
	
	public String designationAndDepartmentNameByDesignationId(String designationId) 
	{
		String name = "";
		
		try(Connection conn = DataBaseConnection.JAVAConnection())
		{ 
			String query = " select * from hrm_basic where id = ?";
			
			try(PreparedStatement ps = conn.prepareStatement(query))
			{	
			   ps.setString(1, designationId);
			   
			   ResultSet rs = ps.executeQuery();
			   if(rs.next())
			   {
				   name = rs.getString("name");   
			   }
			}
			catch(Exception e) 
			{	
				e.printStackTrace();	
			}
		}
		catch(Exception e) 
		{	
			e.printStackTrace();	
		}
		
		return name;
	}
	
	
	
	public int countPresentDays(String userid, Date startDate, Date endDate) 
	{
	    int count = 0;

	    try (Connection conn = DataBaseConnection.JAVAConnection()) 
	    {
	        String sql = "SELECT COUNT(*) AS total FROM attendance_table WHERE userid = ? AND attendance_date BETWEEN ? AND ? AND "
	        		   + "branch_id = ? ";
	        
	        try (PreparedStatement ps = conn.prepareStatement(sql)) 
	        {
	            ps.setString(1, userid);
	            ps.setString(2, sdf1.format(startDate));
	            ps.setString(3, sdf1.format(endDate));
	            ps.setInt(4, branchId);

	            ResultSet rs = ps.executeQuery();
	            if (rs.next()) count = rs.getInt("total");
	        }
	    } 
	    catch (Exception e) 
	    {
	        e.printStackTrace();
	    }
	    
	    return count;
	}



	public int countSundays(Date startDate, Date endDate) 
	{
	    Calendar cal = Calendar.getInstance();
	    cal.setTime(startDate);

	    int count = 0;
	    while (!cal.getTime().after(endDate)) 
	    {
	        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) count++;
	        cal.add(Calendar.DATE, 1);
	    }
	    
	    return count;
	}



	public int getDaysBetween(Date start, Date end) 
	{
	    long diff = end.getTime() - start.getTime();
	    return (int) ((diff / (1000 * 60 * 60 * 24)) + 1);
	}

	
	
	public boolean checkEmpAttendanceOfCurrentDate(String userid, String ad) 
	{
		try(Connection conn=DataBaseConnection.JAVAConnection())
		{
			String qq = "select * from attendance_table where attendance_date = ? and userid = ? and branch_id = ? ";
			
			try(PreparedStatement ps = conn.prepareStatement(qq)) 
			{
				ps.setString(1, ad);
				ps.setString(2, userid);
				ps.setInt(3, branchId);
				
				ResultSet rr = ps.executeQuery();
				if(rr.next())
				{
					return true;
				}
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

		return false;
	}
	
	
	
	public int totalCountByType(String fromDate, String toDate)
	{
		try(Connection conn = DataBaseConnection.JAVAConnection()) 
		{
			String qq = "";
			
			try(PreparedStatement ps = conn.prepareStatement(qq)) 
			{
				
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		return 0;
	}
	
	

public void searchData()
	{
	    System.out.println("METHOD ATTENDANCE HIT");
	    try
	    {
	        HttpSession ss = (HttpSession) FacesContext
	                .getCurrentInstance()
	                .getExternalContext()
	                .getSession(false);

	        int branchId = (int) ss.getAttribute("branchId");

	        System.out.println("empUserId = " + empUserId);
	        System.out.println("startDate = " + startDate);
	        System.out.println("endDate = " + endDate);
	        System.out.println("branchId = " + branchId);

	        show = true;
            
	        viewAttendanceByEmpUserId(empUserId, startDate, endDate, branchId);

	        System.out.println("FINAL LIST SIZE = " + 
	                (empAttendanceList == null ? "NULL" : empAttendanceList.size()));

	    }
	    catch(Exception e)
	    {
	        e.printStackTrace();
	    }
	}

	
	
public void viewSelfie(String selfie) {

    System.out.println("================================");
    System.out.println("SELFIE PATH = " + selfie);
    System.out.println("================================");

    this.selectedSelfie = selfie;
}
	
	
	public void viewAttendanceByEmpUserId(String userId, Date startDate, Date endDate, int branchId) 
	{ 
		empAttendanceList = new ArrayList<>();
	    int count = 1 ;
		
		SimpleDateFormat sf=new SimpleDateFormat("dd/MM/yyyy");
		SimpleDateFormat sdfForDb=new SimpleDateFormat("yyyy-MM-dd");   // For Database query	
		
		try(Connection conn = DataBaseConnection.JAVAConnection()){
		 
			String qq="select * from attendance_table where userid=? and attendance_date>=? and attendance_date<=? ";
		    
			try(PreparedStatement ps = conn.prepareStatement(qq)){
				
				ps.setString(1, userId);
				SimpleDateFormat dbDateFormat = new SimpleDateFormat("yyyy-MM-dd");

				ps.setString(2, dbDateFormat.format(startDate));
				ps.setString(3, dbDateFormat.format(endDate));
//				
				
				 ResultSet rr1 = ps.executeQuery();
				 System.out.println(qq);
				 while(rr1.next())
					{   
						System.out.println("value inn :");
						
						
						EmpInfo ee=new EmpInfo();
						
						ee.setSno(count++);
						String attendanceDate = rr1.getString("attendance_date");

						System.out.println("ATTENDANCE DATE = " + attendanceDate);

						ee.setStrAttendanceDate(attendanceDate);
						ee.setLoginTime(rr1.getString("start_time"));
						ee.setLogoutTime(rr1.getString("end_time"));
						
						if(rr1.getString("end_time")!=null && !rr1.getString("end_time").equalsIgnoreCase(""))
						{
							ee.setWorkingHours("Work Pending");
						}
						ee.setStatus(rr1.getString("status"));
						ee.setLoginDeviceName(rr1.getString("login_device_name"));
						ee.setLogoutDeviceName(rr1.getString("logout_device_name"));
						ee.setLatitudeLogin(rr1.getString("latitude_login"));
						ee.setLongitudeLogin(rr1.getString("longitude_login"));
						ee.setLatitudeLogout(rr1.getString("latitude_logout"));
						ee.setLongitudeLogout(rr1.getString("longitude_logout"));
						String selfiePath = rr1.getString("selfie_path");
						String logoutSelfiePath = rr1.getString("logout_selfie_path");

						System.out.println("=================================");
						System.out.println("SELFIE PATH FROM DB = " + selfiePath);
						System.out.println("ONLINE FILE PATH = " + onlineFileViewPath);
						System.out.println("FINAL IMAGE URL = " + onlineFileViewPath + selfiePath);
						System.out.println("=================================");

						ee.setSelfie(selfiePath);
						ee.setLogoutSelfie(logoutSelfiePath);
						
						
	                    
						empAttendanceList.add(ee);
						
					}
				
				
			}catch(Exception e) {
				
				e.printStackTrace();
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			
		}
		

	}
	
	
	public ArrayList<SelectItem> getEmpList() {
		return empList;
	}

	public void setEmpList(ArrayList<SelectItem> empList) {
		this.empList = empList;
	}

	public String getEmpUserId() {
		return empUserId;
	}

	public void setEmpUserId(String empUserId) {
		this.empUserId = empUserId;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public boolean isShow() {
		return show;
	}

	public void setShow(boolean show) {
		this.show = show;
	}

	public ArrayList<EmpInfo> getEmpAttendanceList() {
		return empAttendanceList;
	}

	public void setEmpAttendanceList(ArrayList<EmpInfo> empAttendanceList) {
		this.empAttendanceList = empAttendanceList;
	}








	public ArrayList<EmpInfo> getEmployees() {
		return employees;
	}








	public void setEmployees(ArrayList<EmpInfo> employees) {
		this.employees = employees;
	}








	public ArrayList<String> getDaysOfMonth() {
		return daysOfMonth;
	}








	public void setDaysOfMonth(ArrayList<String> daysOfMonth) {
		this.daysOfMonth = daysOfMonth;
	}





	public ArrayList<EmpInfo> getAttendnceReportList() {
		return attendnceReportList;
	}





	public void setAttendnceReportList(ArrayList<EmpInfo> attendnceReportList) {
		this.attendnceReportList = attendnceReportList;
	}



	public ArrayList<String> getDateList() {
		return dateList;
	}



	public void setDateList(ArrayList<String> dateList) {
		this.dateList = dateList;
	}



	public ArrayList<SelectItem> getEmpSe() {
		return empSe;
	}



	public void setEmpSe(ArrayList<SelectItem> empSe) {
		this.empSe = empSe;
	}



	public int getBranchId() {
		return branchId;
	}



	public void setBranchId(int branchId) {
		this.branchId = branchId;
	}



	public int getBranchIds() {
		return branchIds;
	}



	public void setBranchIds(int branchIds) {
		this.branchIds = branchIds;
	}



	public String getSelectedSelfie() {
		return selectedSelfie;
	}



	public void setSelectedSelfie(String selectedSelfie) {
		this.selectedSelfie = selectedSelfie;
	}



	public String getOnlineFileViewPath() {
		return onlineFileViewPath;
	}



	public void setOnlineFileViewPath(String onlineFileViewPath) {
		this.onlineFileViewPath = onlineFileViewPath;
	}



	public String getImagePath() {
		return imagePath;
	}



	public void setImagePath(String imagePath) {
		this.imagePath = imagePath;
	}

}