// localStorage.removeItem('calendarAttendance');

const calendar = document.getElementById("calendar");
const monthSelect = document.getElementById("month-year");
const employeeSelect = document.getElementById("employee_name");

// Set current month and year
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');
monthSelect.value = `${currentYear}-${currentMonth}`;

let statusCounts = {
    daysWorked: 0,
    sundaysEligible: 0,
    holidays: 0,
    earnedLeave: 0,
    leaveEnjoyed: 0,
    totalPaidDays: 0,
    absent: 0,
    firstShift: 0,
    nightShift: 0,
    otHours: 0,
    shortageHours: 0
};

// Update summary display
function updateCounts() {
    document.getElementById("days-worked").textContent = statusCounts.daysWorked;
    document.getElementById("sundays-eligible").textContent = statusCounts.sundaysEligible;
    document.getElementById("holiday-count").textContent = statusCounts.holidays;
    document.getElementById("earned-leave").textContent = statusCounts.earnedLeave;
    document.getElementById("enjoy-leave-count").textContent = statusCounts.leaveEnjoyed;
    document.getElementById("balance-leave-count").textContent = statusCounts.balanceLeave;
    document.getElementById("total-paid-days").textContent = statusCounts.totalPaidDays;
    document.getElementById("absent-count").textContent = statusCounts.absent;
    document.getElementById("first-shift-count").textContent = statusCounts.firstShift;
    document.getElementById("night-shift-count").textContent = statusCounts.nightShift;
    document.getElementById("ot-hours").textContent = statusCounts.otHours;
    document.getElementById("shortage-hours").textContent = statusCounts.shortageHours;
}

// Create calendar based on month-year and employee selection
// function createCalendar() {
//     calendar.innerHTML = ""; // Reset calendar

//     let monthYear = monthSelect.value;
//     let [year, month] = monthYear.split("-");
//     let employeeId = employeeSelect.value;
//     if (!employeeId) return; // Ensure an employee is selected

//     let daysInMonth = new Date(year, month, 0).getDate();
//     // let attendanceData = JSON.parse(localStorage.getItem("AttendanceData")) || {};
//     let attendanceData = dummyData;

//     statusCounts = { daysWorked: 0, sundaysEligible: 0, holidays: 0, leaveEnjoyed: 0, totalPaidDays: 0, absent: 0, firstShift: 0, nightShift: 0, otHours: 0, shortageHours: 0 };

//     for (let i = 1; i <= daysInMonth; i++) {
//         let dayDiv = document.createElement("div");
//         dayDiv.classList.add("day");
//         dayDiv.textContent = i;

//         let attendanceDiv = document.createElement("div");
//         attendanceDiv.classList.add("attendance");

//         let dateKey = `${year}-${month}-${String(i).padStart(2, '0')}`;
//         let record = attendanceData[employeeId]?.[dateKey] || "P"; // Default to Present


//         if (record === "A") {
//             dayDiv.classList.add("absent");
//             attendanceDiv.textContent = 'Absent';
//             statusCounts.absent++;
//         } else if (record === "H") {
//             dayDiv.classList.add("holiday");
//             attendanceDiv.textContent = 'Holiday';
//             statusCounts.holidays++;
//         } else if (record === "L") {
//             dayDiv.classList.add("enjoy-leave");
//             attendanceDiv.textContent = 'Leave';
//             statusCounts.leaveEnjoyed++;
//         } else {
//             dayDiv.classList.add("present");
//             attendanceDiv.textContent = 'Present';
//             statusCounts.daysWorked++;
//         }

//         if (new Date(year, month - 1, i).getDay() === 0) {
//             dayDiv.classList.add("sunday");
//             statusCounts.sundaysEligible++;
//         }

//         statusCounts.totalPaidDays = statusCounts.daysWorked + statusCounts.sundaysEligible + statusCounts.holidays;
//         statusCounts.shortageHours = (statusCounts.absent * 8) - statusCounts.otHours;

//         dayDiv.appendChild(attendanceDiv);
//         calendar.appendChild(dayDiv);
//     }

//     updateCounts();
// }


function createCalendar() {
    calendar.innerHTML = "";

    let monthYear = monthSelect.value;
    let [year, month] = monthYear.split("-");
    let employeeId = employeeSelect.value;
    if (!employeeId) return;

    let daysInMonth = new Date(year, month, 0).getDate();
    let firstDayOfMonth = new Date(year, month - 1, 1).getDay();
    let attendanceData = JSON.parse(localStorage.getItem("calendarAttendance")) || [];

    // **Initialize Monthly Summary Counts**
    statusCounts = { 
        daysWorked: 0, 
        sundaysEligible: 0, 
        holidays: 0, 
        earnedLeave: 0, 
        leaveEnjoyed: 0, 
        balanceLeave: 0, 
        totalPaidDays: 0, 
        absent: 0, 
        firstShift: 0, 
        nightShift: 0, 
        otHours: 0, 
        shortageHours: 0 
    };

    // **Create Top Bar for Weekdays**
    let weekdaysRow = document.createElement("div");
    weekdaysRow.classList.add("weekdays-row");

    const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    weekdays.forEach(day => {
        let dayDiv = document.createElement("div");
        dayDiv.classList.add("weekday");
        dayDiv.textContent = day;
        weekdaysRow.appendChild(dayDiv);
    });

    calendar.appendChild(weekdaysRow);

    let daysRow = document.createElement("div");
    daysRow.classList.add("days-row");

    // **Add empty divs for alignment (before 1st day of the month)**
    for (let i = 0; i < firstDayOfMonth; i++) {
        let emptyDiv = document.createElement("div");
        emptyDiv.classList.add("day", "empty-day");
        daysRow.appendChild(emptyDiv);
    }

    // **Generate Calendar Days**
    for (let i = 1; i <= daysInMonth; i++) {
        let dayDiv = document.createElement("div");
        dayDiv.classList.add("day");
        dayDiv.textContent = i;

        let attendanceDiv = document.createElement("div");
        attendanceDiv.classList.add("attendance");

        let dateKey = `${String(i).padStart(2, '0')}-${month}-${year}`; // Format: DD-MM-YYYY
        let record = attendanceData.find(entry => entry["Date"] === dateKey && entry["Employee ID"] == employeeId);

        if (record) {
            if (record["Present"] === "P") {
                dayDiv.classList.add("present");
                attendanceDiv.textContent = 'Present';
                statusCounts.daysWorked++;
            } else if (record["Absent"] === "A") {
                dayDiv.classList.add("absent");
                attendanceDiv.textContent = 'Absent';
                statusCounts.absent++;
            } else if (record["Holiday"] === "H") {
                dayDiv.classList.add("holiday");
                attendanceDiv.textContent = 'Holiday';
                statusCounts.holidays++;
            } else if (record["Leave Enjoyed"]) {
                dayDiv.classList.add("enjoy-leave");
                attendanceDiv.textContent = 'Leave';
                statusCounts.leaveEnjoyed++;
            } else {
                attendanceDiv.textContent = '-';
            }

            // **Summing up values for the month**
            statusCounts.firstShift += record["1St Shift"] ? parseInt(record["1St Shift"]) : 0;
            statusCounts.nightShift += record["Night Shift"] ? parseInt(record["Night Shift"]) : 0;
            statusCounts.otHours += record["OT Hours"] ? timeStringToMinutes(record["OT Hours"]) : 0;
            statusCounts.shortageHours += record["Shortage Hours"] ? timeStringToMinutes(record["Shortage Hours"]) : 0;
        } else {
            attendanceDiv.textContent = '-';
        }

        if (new Date(year, month - 1, i).getDay() === 0) {
            dayDiv.classList.add("sunday");
            statusCounts.sundaysEligible++;
        }

        dayDiv.appendChild(attendanceDiv);
        daysRow.appendChild(dayDiv);

        // **Start a new row after every 7 days**
        if ((i + firstDayOfMonth) % 7 === 0 || i === daysInMonth) {
            calendar.appendChild(daysRow);
            daysRow = document.createElement("div");
            daysRow.classList.add("days-row");
        }
    }

    // **Calculate Final Monthly Summary Values**
    statusCounts.totalPaidDays = statusCounts.daysWorked + statusCounts.sundaysEligible + statusCounts.holidays;
    statusCounts.shortageHours = (statusCounts.absent * 8 * 60) - statusCounts.otHours;

    if (statusCounts.daysWorked >= 20) {
        statusCounts.earnedLeave = 1;
        statusCounts.balanceLeave++;
    }

    statusCounts.balanceLeave -= statusCounts.leaveEnjoyed;

    // Convert OT and Shortage Hours back to HH:MM format
    statusCounts.otHours = minutesToTimeString(statusCounts.otHours);
    statusCounts.shortageHours = minutesToTimeString(statusCounts.shortageHours);

    updateCounts();
}

// **Helper function to convert HH:MM time to total minutes**
function timeStringToMinutes(timeStr) {
    if (!timeStr || timeStr === "00:00") return 0;
    let [hours, minutes] = timeStr.split(":").map(Number);
    return (hours * 60) + minutes;
}

// **Helper function to convert minutes to HH:MM format**
function minutesToTimeString(minutes) {
    let hours = Math.floor(minutes / 60);
    let mins = minutes % 60;
    return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
}


// function createCalendar() {
//     calendar.innerHTML = "";

//     let monthYear = monthSelect.value;
//     let [year, month] = monthYear.split("-");
//     let employeeId = employeeSelect.value;
//     if (!employeeId) return;

//     let daysInMonth = new Date(year, month, 0).getDate();
//     let firstDayOfMonth = new Date(year, month - 1, 1).getDay();
//     // let attendanceData = dummyData;
//     let attendanceData = JSON.parse(localStorage.getItem("calendarAttendance")) || {};

//     statusCounts = { daysWorked: 0, sundaysEligible: 0, holidays: 0, earnedLeave: 0, leaveEnjoyed: 0,balanceLeave: 0, totalPaidDays: 0, absent: 0, firstShift: 0, nightShift: 0, otHours: 0, shortageHours: 0 };

//     // **Create Top Bar for Weekdays**
//     let weekdaysRow = document.createElement("div");
//     weekdaysRow.classList.add("weekdays-row");

//     const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
//     weekdays.forEach(day => {
//         let dayDiv = document.createElement("div");
//         dayDiv.classList.add("weekday");
//         // if (day === "Sun") dayDiv.classList.add("sunday"); // Highlight Sundays
//         dayDiv.textContent = day;
//         weekdaysRow.appendChild(dayDiv);
//     });

//     calendar.appendChild(weekdaysRow);

//     let daysRow = document.createElement("div");
//     daysRow.classList.add("days-row");

//     // **Add empty divs for alignment (before 1st day of the month)**
//     for (let i = 0; i < firstDayOfMonth; i++) {
//         let emptyDiv = document.createElement("div");
//         emptyDiv.classList.add("day", "empty-day");
//         daysRow.appendChild(emptyDiv);
//     }

//     // **Generate Calendar Days**
//     for (let i = 1; i <= daysInMonth; i++) {
//         let dayDiv = document.createElement("div");
//         dayDiv.classList.add("day");
//         dayDiv.textContent = i;

//         let attendanceDiv = document.createElement("div");
//         attendanceDiv.classList.add("attendance");

//         let dateKey = `${year}-${month}-${String(i).padStart(2, '0')}`;
//         let record = attendanceData[employeeId]?.[dateKey] || "";

//         if (record === "A") {
//             dayDiv.classList.add("absent");
//             attendanceDiv.textContent = 'Absent';
//             statusCounts.absent++;
//         } else if (record === "H") {
//             dayDiv.classList.add("holiday");
//             attendanceDiv.textContent = 'Holiday';
//             statusCounts.holidays++;
//         } else if (record === "L") {
//             dayDiv.classList.add("enjoy-leave");
//             attendanceDiv.textContent = 'Leave';
//             statusCounts.leaveEnjoyed++;
//         } else if (record === "P") {
//             dayDiv.classList.add("present");
//             attendanceDiv.textContent = 'Present';
//             statusCounts.daysWorked++;
//         }else {
//             attendanceDiv.textContent = '-';
//         }

//         if (new Date(year, month - 1, i).getDay() === 0) {
//             dayDiv.classList.add("sunday");
//             statusCounts.sundaysEligible++;
//         }

//         statusCounts.totalPaidDays = statusCounts.daysWorked + statusCounts.sundaysEligible + statusCounts.holidays;
//         statusCounts.shortageHours = (statusCounts.absent * 8) - statusCounts.otHours;

//         dayDiv.appendChild(attendanceDiv);
//         daysRow.appendChild(dayDiv);

//         // **Start a new row after every 7 days**
//         if ((i + firstDayOfMonth) % 7 === 0 || i === daysInMonth) {
//             calendar.appendChild(daysRow);
//             daysRow = document.createElement("div");
//             daysRow.classList.add("days-row");
//         }
//         if(statusCounts.daysWorked >= 20){
//             statusCounts.earnedLeave = 1;
//             statusCounts.balanceLeave++;
//         }
//     }
//     statusCounts.balanceLeave = statusCounts.balanceLeave - statusCounts.leaveEnjoyed;
//     updateCounts();
// }

// Event Listeners for Employee and Month-Year selection
monthSelect.addEventListener("change", createCalendar);
employeeSelect.addEventListener("change", createCalendar);

// Initial calendar load
createCalendar();

// -------------------------------------------------------------------------------------------------------------

// Event listener for month/year selection change
monthSelect.addEventListener("input", function () {
    createCalendar(this.value);
});
// Event listener for month/year selection change
employeeSelect.addEventListener("change", function () {
    createCalendar(monthSelect.value);
});
// Create the calendar on page load with the initial value of the input
createCalendar(monthSelect.value);


const employeeNameDropdown = document.getElementById('employee_name');

// Retrieve employeesData from local storage
const employeesData = JSON.parse(localStorage.getItem('employeesData')) || [];

// Populate Employee Name dropdown on page load
function populateEmployeeNameDropdown() {
    // Clear existing options
    employeeNameDropdown.innerHTML = '<option value="">Select Employee Name</option>';

    // Add options dynamically from employeesData
    employeesData.forEach(employee => {
        const option = document.createElement('option');
        option.value = employee.employeeId1;
        option.textContent = employee.employeeId1+'-'+employee.employeeName;
        employeeNameDropdown.appendChild(option);
    });
}

populateEmployeeNameDropdown();


// ----------------------------------------------------------------------------------------------------------

const dummyData = {
    "1001": {
        "2025-03-01": "P", "2025-03-02": "A", "2025-03-03": "P", "2025-03-04": "H", "2025-03-05": "L",
        "2025-03-06": "P", "2025-03-07": "P", "2025-03-08": "A", "2025-03-09": "P", "2025-03-10": "H",
        "2025-03-11": "P", "2025-03-12": "L", "2025-03-13": "P", "2025-03-14": "P", "2025-03-15": "P",
        "2025-03-16": "A", "2025-03-17": "P", "2025-03-18": "H", "2025-03-19": "P", "2025-03-20": "P",
        "2025-03-21": "L", "2025-03-22": "P", "2025-03-23": "A", "2025-03-24": "P", "2025-03-25": "P",
        "2025-03-26": "H", "2025-03-27": "P", "2025-03-28": "P", "2025-03-29": "P", "2025-03-30": "P",
        "2025-03-31": "P"
    },
    "1002": {
        "2025-03-01": "A", "2025-03-02": "P", "2025-03-03": "P", "2025-03-04": "P", "2025-03-05": "H",
        "2025-03-06": "L", "2025-03-07": "P", "2025-03-08": "A", "2025-03-09": "P", "2025-03-10": "P",
        "2025-03-11": "P", "2025-03-12": "H", "2025-03-13": "P", "2025-03-14": "L", "2025-03-15": "P",
        "2025-03-16": "P", "2025-03-17": "A", "2025-03-18": "P", "2025-03-19": "P", "2025-03-20": "H",
        "2025-03-21": "P", "2025-03-22": "L", "2025-03-23": "P", "2025-03-24": "P", "2025-03-25": "A",
        "2025-03-26": "P", "2025-03-27": "P", "2025-03-28": "H", "2025-03-29": "P", "2025-03-30": "L",
        "2025-03-31": "P"
    }
};

// Trigger the modal when the Import button is clicked
document.getElementById('import-button').addEventListener('click', function() {
    $('#importModal').modal('show');
});

function importExcel() {
    let fileInput = document.getElementById('excelFile');
    let file = fileInput.files[0]; // Get the uploaded file
    if (!file) {
        alert("Please select an Excel file.");
        return;
    }

    const reader = new FileReader();
    
    reader.onload = function (e) {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });

        const sheetName = workbook.SheetNames[0]; // Assuming data is in the first sheet
        const sheet = workbook.Sheets[sheetName];

        let jsonData = XLSX.utils.sheet_to_json(sheet, { defval: "" });
        
        // Convert Date and Time columns
        jsonData = jsonData.map(row => {
            if (row.Date) {
                row.Date = excelDateToJSDate(row.Date);
            }
            if (row["OT Hours"]) {
                row["OT Hours"] = excelTimeToJSTime(row["OT Hours"]); 
            }
            if (row["Shortage Hours"]) {
                row["Shortage Hours"] = excelTimeToJSTime(row["Shortage Hours"]);
            }
            return row;
        });

        // Save to local storage
        localStorage.setItem("calendarAttendance", JSON.stringify(jsonData));
        $('#importModal').modal('hide');
        alert("Excel data imported successfully!");
        console.log("Imported Data:", jsonData);
    };

    reader.readAsArrayBuffer(file);
}

// Function to convert Excel numeric date to JavaScript Date
function excelDateToJSDate(excelDate) {
    if (!excelDate) return '';
    const parsedDate = new Date((excelDate - 25569) * 86400 * 1000);
    const day = String(parsedDate.getDate()).padStart(2, '0');
    const month = String(parsedDate.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
    const year = parsedDate.getFullYear();
    return `${day}-${month}-${year}`;
}

// Function to convert Excel decimal time to HH:MM format
function excelTimeToJSTime(excelTime) {
    if (!excelTime || isNaN(excelTime)) return '00:00';
    
    let totalMinutes = Math.round(excelTime * 24 * 60); // Convert fraction to total minutes
    let hours = Math.floor(totalMinutes / 60);
    let minutes = totalMinutes % 60;

    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
}

// Utility function to convert DD-MM-YYYY to YYYY-MM-DD
function convertDateToISO(dateString) {
    if (!dateString) return ''; // Return empty string for invalid or empty date
    const [day, month, year] = dateString.split('-');
    return `${year}-${month}-${day}`;
}
// Utility function to convert DD-MM-YYYY to YYYY-MM-DD
function convertDateToddmmyyyy(dateString) {
    if (!dateString) return ''; // Return empty string for invalid or empty date
    const [year, month, day] = dateString.split('-');
    return `${day}-${month}-${year}`;
}

console.log(JSON.parse(localStorage.getItem("calendarAttendance")));