jQuery(document).ready(function ($) {
    var lastLoadedPage = null;
    var isAjaxLoading = false;

    // Function to get the current page from the URL
    function getPageFromURL() {
        const path = window.location.pathname;
        const match = path.match(/\/user-dashboard\/([^\/]*)/);
       // alert(path);
        return match && match[1] ? match[1] : "dashboard";
    }

    // Function to load the page from URL (handles refresh)
    function loadPageFromURL() {
        var page = getPageFromURL();
        loadDashboardContent(page, false);
    }

    function getProjectIdFromURL() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get("project_id") || 0;
    }

    // Function to load dashboard content via AJAX
    function loadDashboardContent(page, updateURL = true) {
        if (isAjaxLoading || lastLoadedPage === page) {
            return;
        }


        isAjaxLoading = true;
        lastLoadedPage = page;
        let projectId = getProjectIdFromURL();

        jQuery.ajax({
            url: voidempo_path.ajaxurl,
            type: "POST",
            dataType: "json",
            data: {
                action: "voidempo_load_dashboard_content",
                page: page,
                project_id: projectId,
                timestamp: new Date().getTime(),
                security: voidempo_path.VOIDEMPO_nonce,
            },
            success: function (response) {
                if (response.success) {

                    jQuery("#dashboard-content").html(response.data.html);
                    initAddProjectJS();
                    page = page.toLowerCase();

                    if (voidempo_path.page_styles[page]) {
                        loadCSS(voidempo_path.page_styles[page]);
                    }
                } else {
                    let message = response.data?.message?.toLowerCase().trim();
                    if (message && message.includes("security check failed")) {
                        window.location.replace(voidempo_path.login_url);
                    } else {
                        jQuery("#dashboard-content").html('<p style="color: red;">' + response.data.message + '</p>');
                    }
                }

                // Update browser URL (without reloading)
                if (updateURL && page && typeof page === "string" && page !== "undefined") {
                    var newUrl = voidempo_path.dashboard_base + page;
                    history.pushState({ page: page }, "", newUrl);
                }

                setTimeout(loadTableData, 500);
                setTimeout(function () {
                    jQuery(document).trigger('menuContentLoaded', [page.toLowerCase()]);
                }, 500);

            },
            error: function () {
                jQuery("#dashboard-content").html('<p style="color: red;">Error loading content.</p>');
            },
            complete: function () {
                isAjaxLoading = false;
            }
        });
    }


    // Handle menu item clicks
    jQuery(document).on("click", ".menu-item, .load-page-btn ,.submenu-item", function (e) {
        e.preventDefault();
        const page = jQuery(this).data("page");
        if (!page || page === "undefined") {
            console.warn("Invalid page clicked:", page);
            return;
        }
        loadDashboardContent(page);
    });

    // Handle browser back/forward button clicks
    window.onpopstate = function (event) {
        if (event.state && event.state.page) {
            loadDashboardContent(event.state.page, false);
        } else {
            loadPageFromURL();
        }
    };

    // Initial load on page refresh
    loadPageFromURL();

    function loadCSS(url) {
        if (!url) {
            console.warn("loadCSS() called without a valid URL");
            return;
        }

        document.querySelectorAll("link[data-page-style]").forEach(link => link.remove());
        const link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = url + "?v=" + new Date().getTime(); 
        link.setAttribute("data-page-style", "true");

        document.head.appendChild(link);
    }


	function initAddProjectJS() {
		var managerSelect = document.getElementById("voidempo_project_manager");
		var membersSelect = document.getElementById("voidempo_project_members");

		if (managerSelect && membersSelect) {
			managerSelect.addEventListener("change", function () {
				var selectedManager = managerSelect.value;
				for (var i = 0; i < membersSelect.options.length; i++) {
					membersSelect.options[i].disabled = false;
					if (membersSelect.options[i].value === selectedManager) {
						membersSelect.options[i].disabled = true;
					}
				}
			});

			$(membersSelect).select2();

			if (managerSelect.value !== "0") {
				for (var i = 0; i < membersSelect.options.length; i++) {
					if (membersSelect.options[i].value === managerSelect.value) {
						membersSelect.options[i].disabled = true;
					}
				}
			}
		}

		$('#voidempo_project_members').select2({
			placeholder: '-- Assign Members --',
			closeOnSelect: false
		});

		$('#voidempo_project_start_date, #voidempo_project_end_date').datepicker({
			dateFormat: 'yy-mm-dd'
		});
	}

    function reinitializeDateRangePicker() {

        var savedStart = localStorage.getItem('daterangepicker_start');
        var savedEnd = localStorage.getItem('daterangepicker_end');

        var start = savedStart ? moment(savedStart, 'YYYY-MM-DD') : moment().subtract(1, 'days');
        var end = savedEnd ? moment(savedEnd, 'YYYY-MM-DD') : moment().subtract(1, 'days');


        if (jQuery('#durationselection_').data('daterangepicker')) {
            jQuery('#durationselection_').data('daterangepicker').remove();
        }

        jQuery('#durationselection_').daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            linkedCalendars: false,
            autoUpdateInput: false,
            startDate: start,
            endDate: end,
            maxDate: moment().subtract(1, 'days')
        }, function (start, end) {

            jQuery('#durationselection_').val(start.format('YYYY/MM/DD') + ' - ' + end.format('YYYY/MM/DD'));
            jQuery('#from_date').val(start.format('YYYY-MM-DD')).trigger('change');
            jQuery('#to_date').val(end.format('YYYY-MM-DD')).trigger('change');


            localStorage.setItem('daterangepicker_start', start.format('YYYY-MM-DD'));
            localStorage.setItem('daterangepicker_end', end.format('YYYY-MM-DD'));
        });
        jQuery('#durationselection_').val(start.format('YYYY/MM/DD') + ' - ' + end.format('YYYY/MM/DD'));
    }


    jQuery(document).ajaxComplete(function () {
        reinitializeDateRangePicker();
    });

    jQuery(document).ready(function () {
        reinitializeDateRangePicker();
    });

    window.addEventListener('pageshow', function () {
        reinitializeDateRangePicker();
    });

	jQuery(document).on('change', '#voidempo_task_project', function() {
        var project_id = jQuery(this).val();

        jQuery.ajax({
            type: 'POST',
            url: voidempo_path.ajaxurl,
            data: {
                action: 'voidempo_get_project_members',
                project_id: project_id,
                security: voidempo_path.VOIDEMPO_nonce
            },
            success: function(response) {
                jQuery('#voidempo_create_task_manager').html(response.managers);
                jQuery('#voidempo_taskc_assign_mem').html(response.members);
            },
            error: function(xhr, status, error) {
                console.error("AJAX error:", status, error);
            }
        });
    });

    jQuery(document).on('change', '#report_project_filter', function() {
            var projectId = $(this).val();
            $.ajax({
                url: voidempo_path.ajaxurl,
                type: 'POST',
                data: {
                    action: 'voidempo_get_tasks_by_project',
                    project_id: projectId,
                    security: voidempo_path.VOIDEMPO_nonce
                },
                success: function(response) {
                    $('#report_task_filter').html(response);
                },
                error: function() {
                    alert('Failed to fetch tasks. Please try again.');
                }
            });
        });
        
      jQuery(document).on('change', '#eod_project_filter', function() {
		var selectedProject = $(this).val();

		$.ajax({
			url: voidempo_path.ajaxurl,
			type: 'POST',
			data: {
				action: 'voidempo_get_project_tasks', 
				project_id: selectedProject,                    
				security :voidempo_path.VOIDEMPO_nonce,

			},
			success: function(response) {
				$('#eod_task_filter').html(response);
			},
			error: function(error) {
				console.log('Error:', error);
			}
		});
	});

    function calendar() {
        var calendarEl = document.getElementById('voidempo-calendar');
        if (!calendarEl) return;

        var calendar = new FullCalendar.Calendar(calendarEl, {
            initialView: 'dayGridMonth',
            selectable: true,
            editable: false,

            // Load events via AJAX
            events: function(fetchInfo, successCallback, failureCallback) {
                jQuery.post(voidempo_path.ajaxurl, {
                    action: 'voidempo_get_calendar_events',
                    security: voidempo_path.VOIDEMPO_nonce
                }, function(response) {
                    if (response.success) {
                        let allEvents = [];
                        if (response.data.jsonevent) allEvents = allEvents.concat(response.data.jsonevent);
                        if (response.data.jsonLeaveEvents) allEvents = allEvents.concat(response.data.jsonLeaveEvents);
                        successCallback(allEvents);
                    } else {
                        failureCallback();
                    }
                });
            },

            // Click on any event
            eventClick: function(info) {
                let event = info.event;
                let type = event.extendedProps.event_type || 'unknown';
                alert(
                   event.title 
                   
                );
            },

            // Click on date to open modal
            dateClick: function(info) {
                jQuery("#holiday-start").val(info.dateStr);
                jQuery("#holiday-end").val(info.dateStr);
                jQuery("#holiday-title").val('');
                jQuery("#holiday-halfday").prop('checked', false);
                jQuery("#holidayModal").modal("show");
            },

            // Customize event display
            eventContent: function(arg) {
                let domNodes = [];
                let type = arg.event.extendedProps.event_type || 'unknown';

                let title = document.createElement('span');
                title.innerText = arg.event.title + " ";
                domNodes.push(title);

                // Holiday → edit + delete
                if (type === 'holiday') {
                    let editIcon = document.createElement('span');
                    editIcon.innerHTML = '<i class="fas fa-edit" style="color:white; cursor:pointer; margin-left:5px;"></i>';
                    editIcon.onclick = function(e) {
                        e.stopPropagation();
                        let newTitle = prompt("Edit Holiday Title:", arg.event.title);
                        if (newTitle?.trim() !== "") {
                            jQuery.post(voidempo_path.ajaxurl, {
                                action: 'voidempo_holidays_eventtitle_update',
                                security: voidempo_path.VOIDEMPO_nonce,
                                eventid: arg.event.id,
                                eventtitle: newTitle
                            }, function(response) {
                                if (response === 'updated') {
                                    arg.event.setProp('title', newTitle);
                                    alert('Holiday updated successfully!');
                                } else {
                                    alert('Failed to update holiday.');
                                }
                            });
                        }
                    };
                    domNodes.push(editIcon);

                    let deleteIcon = document.createElement('span');
                    deleteIcon.innerHTML = '<i class="fas fa-trash" style="color:white; cursor:pointer; margin-left:5px;"></i>';
                    deleteIcon.onclick = function(e) {
                        e.stopPropagation();
                        if (confirm("Delete this holiday?")) {
                            jQuery.post(voidempo_path.ajaxurl, {
                                action: "voidempo_holidays_event_delete",
                                id: arg.event.id,
                                security: voidempo_path.VOIDEMPO_nonce
                            }, function(response) {
                                if (response.success) {
                                    arg.event.remove();
                                    alert("Holiday deleted!");
                                } else {
                                    alert("Failed to delete holiday.");
                                }
                            });
                        }
                    };
                    domNodes.push(deleteIcon);

                // Half-day → only delete
                } else if (type === 'half_day') {
                    let deleteIcon = document.createElement('span');
                    deleteIcon.innerHTML = '<i class="fas fa-trash" style="color:white; cursor:pointer; margin-left:5px;"></i>';
                    deleteIcon.onclick = function(e) {
                        e.stopPropagation();
                        if (confirm("Delete this half day?")) {
                            jQuery.post(voidempo_path.ajaxurl, {
                                action: "voidempo_delete_halfday",
                                date: arg.event.startStr,
                                security: voidempo_path.VOIDEMPO_nonce,
                            }, function(response) {
                                if (response.success) {
                                    arg.event.remove();
                                    alert("Half day deleted!");
                                } else {
                                    alert(response.data?.message || "Failed to delete half day.");
                                }
                            });
                        }
                    };
                    domNodes.push(deleteIcon);
                }

                return { domNodes: domNodes };
            }
        });

        calendar.render();

        // Form submission for holiday / half-day
        jQuery(document).off("submit", "#holiday-form").on("submit", "#holiday-form", function(e) {
            e.preventDefault();

            var title = jQuery("#holiday-title").val();
            var start = jQuery("#holiday-start").val();
            var end   = jQuery("#holiday-end").val();
            var half_day = jQuery("#holiday-halfday").is(":checked") ? 1 : 0;

            if (half_day === 1) {
                jQuery.post(voidempo_path.ajaxurl, {
                    action: 'voidempo_save_company_half_day',
                    start: start,
                    security: voidempo_path.VOIDEMPO_nonce
                }, function(response) {
                    if (response.success && response.data.msg === "inserted") {
                        alert("Half Day saved!");
                        calendar.refetchEvents();
                        jQuery("#holidayModal").modal("hide");
                    } else {
                        alert(response.data?.message || "Failed to save half day.");
                    }
                });
            } else {
                jQuery.post(voidempo_path.ajaxurl, {
                    action: 'voidempo_holidays_event_add',
                    title: title,
                    start: start,
                    end: end,
                    security: voidempo_path.VOIDEMPO_nonce,
                }, function(response) {
                    if (response.success) {
                        alert("Holiday added!");
                        calendar.refetchEvents();
                        jQuery("#holidayModal").modal("hide");
                    } else {
                        alert(response.data?.message || "Error saving holiday");
                    }
                });
            }
        });
    }


    function loadTableData() {

        if ($('#voidempo_eod_list_view').length > 0) {
            if ($.fn.DataTable.isDataTable('#voidempo_eod_list_view')) {
                $('#voidempo_eod_list_view').DataTable().clear().destroy();
            }

            jQuery('#voidempo_eod_list_view thead th').each(function (i) {
                const title = jQuery(this).text();
                jQuery(this).html(title + '<br><input type="text" placeholder="Search" class="column-search" data-index="' + i + '" style="width:100%"/>');
            });
            jQuery(document).on('change', '.column-search', function () {
                table.ajax.reload();
            });

            jQuery('#voidempo_eod_list_view thead').on('keyup', '.column-search', function () {
                var colIndex = jQuery(this).data('index');
                table.column(colIndex).search(this.value).draw();
            });

            var table = jQuery('#voidempo_eod_list_view').DataTable({
                destroy: true,
                orderCellsTop: true,
                fixedHeader: true,
                paging: true,
                pageLength: 25,
                dom: 'Bfrtip',
                lengthMenu: [
                    [25, 50, 100, 150, 200, 250],
                    ['25 rows', '50 rows', '100 rows', '150 rows', '200 rows', '250 rows']
                ],
                buttons: [
                    'pageLength',
                    {
                        text: 'Export to excel',
                        className: 'excelButton',
                        action: function (e, dt, node, config) {
                            // Get filter values
                            var fromDate = jQuery('#from_date').val();
                            var toDate = jQuery('#to_date').val();
                            var projectFilter = jQuery('#eod_project_filter').val();
                            var taskFilter = jQuery('#eod_task_filter').val();
                            var columnFilter = jQuery('#search_text').val();
                            jQuery.ajax({
                                url: voidempo_path.ajaxurl,
                                type: 'POST',
                                data: {
                                    action: 'voidempo_func_export_to_excel2',
                                    from_date: fromDate,
                                    to_date: toDate,
                                    project_filter: projectFilter,
                                    task_filter: taskFilter,
                                    columns: columnFilter,
                                    security: voidempo_path.VOIDEMPO_nonce
                                },
                                success: function (response) {
                                    if (response.success && response.data.file) {
                                        var downloadLink = document.createElement("a");
                                        downloadLink.href = response.data.file;
                                        downloadLink.download = 'EOD_list.csv';
                                        document.body.appendChild(downloadLink);
                                        downloadLink.click();
                                        document.body.removeChild(downloadLink);
                                    } else {
                                        alert("Export failed: " + (response.data?.message || "Unknown error"));
                                    }
                                },
                                beforeSend: function () {
                                    jQuery('.lp-ad-screen').show();
                                },
                                complete: function () {
                                    jQuery('.lp-ad-screen').hide();
                                },

                            });
                        }
                    },
                ],
                scrollX: true,
                scrollCollapse: true,
                processing: true,
                serverSide: true,
                ajax: {
                    url: voidempo_path.ajaxurl + '?action=voidempo_filtertableeodlist',
                    type: 'POST',

                    data: function (d) {
                        d.from_date = $('#from_date').val() || '';
                        d.to_date = $('#to_date').val() || '';
                        d.project_filter = $('#eod_project_filter').val() || '';
                        d.task_filter = $('#eod_task_filter').val() || '';
                        d.security = voidempo_path.VOIDEMPO_nonce;
                        return d
                    },
                    beforeSend: function () {
                        $('.lp-ad-screen').show();
                    },
                    complete: function () {
                        $('.lp-ad-screen').hide();
                    }
                }
            });

            let typingTimer;
            jQuery('#voidempo_eod_list_view thead').on('keyup change', '.column-search', function () {
                clearTimeout(typingTimer);
                let input = this;
                typingTimer = setTimeout(function () {
                    var colIndex = jQuery(input).data('index');
                    table.column(colIndex).search(input.value).draw();
                }, 500);
            });

            jQuery(document).on('change', '.date-filter, #eod_project_filter, #eod_task_filter, .column-search', function () {
                table.ajax.reload();
            });
        }

        function loadMissingEOD() {
            var employeename = jQuery('.misemployeename').val();
            var duration = jQuery('.durationselection_').val();

            var $html = 'Search <div class="spinner-border text-light" role="status" style="height: 20px;width: 20px;"> <span class="sr-only">Loading...</span></div>';
            jQuery('.searchmissingeod').html($html);

            var post_data = {
                'employeename': employeename,
                'duration': duration,
                'action': 'voidempo_missing_eod_data',
                'security': voidempo_path.VOIDEMPO_nonce
            };

            jQuery.ajax({
                url: voidempo_path.ajaxurl,
                type: 'POST',
                data: post_data,
                dataType: 'html',
                success: function (response) {
                    jQuery('.voidempo_missingeod_tablediv').html(response);
                    jQuery('.searchmissingeod').html("Search");
                    jQuery('#voidempo_missingeod_table').DataTable();
                }
            });
        }

        jQuery(document).on('click', '.searchmissingeod', function () {
            loadMissingEOD();
        });


        jQuery(document).on('menuContentLoaded', function (e, page) {
            if (page === 'dashboard') {
                loadMissingEOD();
            }
        });

        jQuery(document).on('menuContentLoaded', function (e, page) {
            if (page === 'calendar_view') {
                calendar();
            }
        });

        jQuery(document).on('input', '.voidempo_eod_hours_all', function () {
            var this_al = jQuery(this);
            var uni = jQuery(this).data('rand');
            Number.prototype.padDigit = function () {
                return (this < 10) ? '0' + this : this;
            }

            var t1 = "00:00";
            var mins = 0;
            var hrs = 0;
            var hrsadd = 0;
            var minsadd = 0;
            var total_hr = 0;
            jQuery('.voidempo_eod_hours_all').each(function () {
                if (jQuery(this).val() == '') {
                } else {
                    var inputValue = jQuery(this).val();
                    // Validate input to not allow more than two zeros
                    if (inputValue.match(/0{3,}/)) {
                        jQuery(this).val(inputValue.replace(/0{3,}/g, '00'));
                    }
                    t1 = t1.split(':');
                    var t2 = inputValue.split(':');
                    mins = Number(t1[1]) + Number(t2[1]);
                    minhrs = Math.floor(parseInt(mins / 60));
                    hrs = Number(t1[0]) + Number(t2[0]) + minhrs;
                    mins = mins % 60;
                    hrsadd = hrs.padDigit();
                    minsadd = mins.padDigit();

                    if (isNaN(hrsadd) || isNaN(minsadd)) {
                        jQuery('.invalidhrformat' + uni).html('Invalid format');
                    } else {
                        jQuery('.invalidhrformat' + uni).html('');
                    }

                    if (isNaN(hrsadd)) {
                        hrsadd = '00';
                    }
                    if (isNaN(minsadd)) {
                        minsadd = '00';
                    }
                    t1 = hrsadd + ':' + minsadd;
                }
            });
            jQuery("#voidempo_eod_todays_hours").val(t1);
        });


        if ($('#project-list-table').length > 0) {
            if ($.fn.DataTable.isDataTable('#project-list-table')) {
                $('#project-list-table').DataTable().clear().destroy();
            }

            var table8 = jQuery('#project-list-table').DataTable({
                destroy: true,
                orderCellsTop: true,
                fixedHeader: true,
                  dom: 'Bfrtip',
                lengthMenu: [
                    [25, 50, 100, 150, 200, 250],
                    ['25 rows', '50 rows', '100 rows', '150 rows', '200 rows', '250 rows']
                ],
                buttons: [
                    'pageLength',
                ],
                scrollX: true,
                scrollCollapse: true,
                processing: true,
                serverSide: true,
                ajax: {
                    url: voidempo_path.ajaxurl + '?action=voidempo_fetch_all_projects',
                    type: 'POST',
                    data: function (d) {
                        d.project_filter = $('#project_filter').val() || '';
                        d.status_filter = $('#status_filter').val() || '';
                        d.security = voidempo_path.VOIDEMPO_nonce;
                    },
                    beforeSend: function () {
                        jQuery('.lp-ad-screen').show();
                    },
                    complete: function () {
                        jQuery('.lp-ad-screen').hide();
                    }
                },
            });

            jQuery(document).on('change', '#project_filter, #status_filter', function () {
                table8.ajax.reload();
            });

        }

        if ($('#voidempo_project_view').length > 0) {
            if ($.fn.DataTable.isDataTable('#voidempo_project_view')) {
                $('#voidempo_project_view').DataTable().clear().destroy();
            }
            $('#voidempo_project_view').DataTable({
                order: [[3, "desc"], [0, "asc"]],
                pageLength: 25,
                lengthMenu: [[25, 50, 100], [25, 50, 100]],
                processing: true,
                serverSide: true,
               
                ajax: {
                    url: voidempo_path.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'voidempo_filterprojectlist',
                        security: voidempo_path.VOIDEMPO_nonce
                    },
                    beforeSend: function () {
                        $('.lp-ad-screen').show();
                    },
                    complete: function () {
                        $('.lp-ad-screen').hide();
                    }
                }
            });

        }
        
        function resetForm(formSelector) {
            jQuery(formSelector)[0].reset();
        }

        function showMessage(type, message) {
            var messageClass = type === 'success' ? 'success-message' : 'error-message';
            var messageHtml = "<br><br><center><div class='" + messageClass + "'><h3 class='" + messageClass + "'>" + message + '</h3></div><center>';

            jQuery('.messages').html(messageHtml);
            alert(message);
        }
            jQuery('#leave-type').on('change', function () {
                const leaveType = jQuery(this).val();
                if (leaveType === 'first-half' || leaveType === 'second-half') {
                    jQuery('#to-date-group').hide();
                } else {
                    jQuery('#to-date-group').show();
                }
            });

            jQuery('#from-date').on('change', function () {
                const fromDate = jQuery(this).val();
                jQuery('#to-date').val(fromDate).attr('min', fromDate);
                const month = new Date(fromDate).getMonth() + 1;
                jQuery('#selected_month').val(month);
            });

        jQuery('.leave-form').submit(function (event) {
            event.preventDefault();

            var fromDate = jQuery("#from-date").val();
            var toDate = jQuery("#to-date").val();

            if (toDate === "") {
                jQuery("#to-date").val(fromDate);
            }

            var formData = jQuery(this).serialize();

            jQuery.ajax({
                type: 'POST',
                url: voidempo_path.ajaxurl,
                data: formData + '&action=voidempo_handle_form_submission&security=' + voidempo_path.VOIDEMPO_nonce,

                success: function (response) {
                    table3.ajax.reload();
                    resetForm('.leave-form');
                    showMessage(response.message_type, response.message);
                    jQuery.each(response.data, function (index, rowData) {
                        var row = "<tr>";
                        jQuery.each(rowData, function (colIndex, colData) {
                            if (colIndex === 4 || colIndex === 5) {
                                colData = formatDate(colData);
                            }
                            row += "<td>" + colData + "</td>";
                        });
                        row += "</tr>";
                        jQuery("#leaveApplicationsTable tbody").append(row);
                    });
                },
                beforeSend: function () {

                    jQuery('.lp-ad-screen').show();
                },
                complete: function () {
                    jQuery('.lp-ad-screen').hide();
                },
                error: function (error) {
                    console.error(error);

                }
            });
        });

        const columnKeyMap = {
            'name': 'name',
            'email': 'email',
            'dob': 'dob',
            'joining date': 'joining',
            'starting salary': 'salary',
            'probation end': 'probation',
            'Marital Status':'marital_status',
            'User Marriage Anniversary':'user_marriage_anniversary',
            'spouse_name' : 'spouse_name',
            'spouse_birthday' : 'spouse_birthday',
            'child1_name'     : 'child1_name',
            'child1_birthday' :'child1_birthday',
            'child2_name'     : 'child2_name' ,
            'child2_birthday' : 'child2_birthday',
            'leave details': 'leave_details',
            'actions': 'actions'
        };

        const userTableColumns = [];

        jQuery('#userTable thead th').each(function () {
            let headerText = jQuery(this).text().trim().toLowerCase();

            let dataKey = columnKeyMap[headerText] || headerText.replace(/\s+/g, '_');

            if (dataKey === 'actions') {
                userTableColumns.push({
                    data: 'actions',
                    orderable: false,
                    searchable: false,
                    render: function (data, type, row) {
                        return `
                            <button class="btn btn-primary btn-sm edit-user reg_edit" data-id="${row.id}">Edit</button>
                            <button class="btn btn-danger btn-sm delete-user reg_delete" data-id="${row.id}">Delete</button>
                        `;
                    }
                });
            }
            else if (dataKey === 'leave_details') {
                userTableColumns.push({
                    data: 'leave_details',
                    render: function (data) {
                        return data || 'N/A';
                    }
                });
            } else {
                userTableColumns.push({ data: dataKey });
            }
        });

        if (jQuery('#userTable').length > 0) {
            if (jQuery.fn.DataTable.isDataTable('#userTable')) {
                jQuery('#userTable').DataTable().clear().destroy();
            }

            var userTable = jQuery('#userTable').DataTable({
                destroy: true,
                orderCellsTop: true,
                dom: 'Bfrtip',
                lengthMenu: [
                    [25, 50, 100, 150, 200, 250],
                    ['25 rows', '50 rows', '100 rows', '150 rows', '200 rows', '250 rows']
                ],
                buttons: ['pageLength'],
                scrollX: true,
                scrollCollapse: true,
                processing: true,
                serverSide: false,
                ajax: {
                    url: voidempo_path.ajaxurl,
                    type: 'POST',
                    data: function (d) {
                        d.action = 'voidempo_fetch_user_data';
                        d.security = voidempo_path.VOIDEMPO_nonce;
                    },
                    beforeSend: function () {
                        jQuery('.lp-ad-screen').show();
                    },
                    complete: function () {
                        jQuery('.lp-ad-screen').hide();
                    }
                },
                columns: userTableColumns
            });

            jQuery(document).on('change', '#user_filter', function () {
                userTable.ajax.reload();
            });
        }

        var table3 = jQuery('#leaveApplicationsTable').DataTable({
            "pageLength": 25,
            "lengthMenu": [
                [25, 50, 100, 150, 200, 250],
                ['25 rows', '50 rows', '100 rows', '150 rows', '200 rows', '250 rows']
            ],
            "language": {
                "lengthMenu": "<b>Show Entries:</b> _MENU_"
            },
            "processing": true,
            "serverSide": true,
            "serverMethod": 'post',
            "bPaginate": true,
            "ordering": false,
            "orderCellsTop": true,
            "fixedHeader": true,
            "searching": true,
            "info": true,
            "ajax": {
                url: voidempo_path.ajaxurl,
                type: 'POST',
                data: function (d) {
                    d.action = 'voidempo_get_leave_applications_table_data';
                    d.userId = jQuery('#userFilter').val();
                    d.month = jQuery('#monthFilter').val();
                    d.year = jQuery('#yearFilter').val();
                    d.security = voidempo_path.VOIDEMPO_nonce;
                },
                beforeSend: function () {
                    jQuery('.lp-ad-screen').show();
                },
                complete: function () {
                    jQuery('.lp-ad-screen').hide();
                },
            },
            "dom": 'Bfrtip',
            "buttons": [
                'pageLength',
                {
                    text: 'Excel',
                    className: 'excelButtonn',
                    action: function (e, dt, node, config) {
                        var userId = jQuery('#userFilter').val();
                        var month = jQuery('#monthFilter').val();
                        var year = jQuery('#yearFilter').val();

                        jQuery.ajax({
                            url: voidempo_path.ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'voidempo_export_to_excel_leave',
                                userId: userId,
                                month: month,
                                year: year,
                                security: voidempo_path.VOIDEMPO_nonce,
                            },
                            success: function (response) {
                                if (response.success && response.data?.file) {
                                    const data = response.data;
                                    const downloadLink = document.createElement("a");
                                    downloadLink.href = data.file;
                                    downloadLink.download = data.filename || "download.xlsx";
                                    downloadLink.style.display = "none";
                                    document.body.appendChild(downloadLink);
                                    downloadLink.click();
                                    document.body.removeChild(downloadLink);
                                } else {
                                    alert('Export failed: ' + (response.data?.message || 'Unknown error'));
                                }
                            },

                            beforeSend: function () {
                                jQuery('.lp-ad-screen').show();
                            },
                            complete: function () {
                                jQuery('.lp-ad-screen').hide();
                            }

                        });
                    }
                }
            ]
        });

        jQuery('#leaveApplicationsTable').on('click', '.reject-btn', function () {
            var leaveId = jQuery(this).data('leave-id');

            jQuery.ajax({
                url: voidempo_path.ajaxurl,
                type: 'POST',
                data: {
                    action: 'voidempo_VWFNRejectLeave',
                    leave_id: leaveId,
                    security: voidempo_path.VOIDEMPO_nonce,
                },
                success: function (response) {
                    alert('Leave application rejected successfully!');
                    table3.ajax.reload();
                },
                error: function (error) {
                    console.error(error);
                },
                beforeSend: function () {
                    jQuery('.lp-ad-screen').show();
                },
                complete: function () {
                    jQuery('.lp-ad-screen').hide();
                },
            });
        });
        jQuery('#userFilter, #monthFilter, #yearFilter').on('change', function () {
            table3.ajax.reload();
        });

        jQuery('#leaveApplicationsTable').on('click', '.accept-btn', function () {
            var leaveId = jQuery(this).data('leave-id');

            jQuery.ajax({
                url: voidempo_path.ajaxurl,
                type: 'POST',
                data: {
                    action: 'voidempo_VWFNAcceptLeave',
                    leave_id: leaveId,
                    security: voidempo_path.VOIDEMPO_nonce,
                },
                success: function (response) {
                    alert('Leave application accepted successfully!');
                    table3.ajax.reload();
                },
                error: function (error) {
                    console.error(error);
                },
                beforeSend: function () {
                    jQuery('.lp-ad-screen').show();
                },
                complete: function () {
                    jQuery('.lp-ad-screen').hide();
                },
            });
        });
        
        jQuery('#voidempo_report_table thead tr').clone(true).appendTo('#voidempo_report_table thead');
        jQuery('#voidempo_report_table thead tr:eq(1) th').each(function (i) {
            var title = jQuery(this).text();
            jQuery(this).html('<input type="text" placeholder="Search" />');

            jQuery('input', this).on('keyup change', function () {
                if (table2.column(i).search() !== this.value) {
                    table2
                        .column(i)
                        .search(this.value)
                        .draw();
                }
            });

        });
        var table2 = jQuery('#voidempo_report_table').DataTable({
            orderCellsTop: true,
            fixedHeader: true,
            dom: 'Bfrtip',
            buttons: [ {
                text: 'Export to excel',
                className: 'excelButton',
                action: function (e, dt, node, config) {
                    // Get filter values
                    var fromDate = jQuery('#from_date').val();
                    var toDate = jQuery('#to_date').val();
                    var projectFilter = jQuery('#project_filter_tasksummary').val();
                    var taskFilter = jQuery('#task_filter_tasksummary').val();
                    var columnFilter = jQuery('#search_text').val();

                    jQuery.ajax({
                        url: voidempo_path.ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'voidempo_func_export_to_excel3',
                            from_date: fromDate,
                            to_date: toDate,
                            project_filter: projectFilter,
                            task_filter: taskFilter,
                            columns: columnFilter,
                            security: voidempo_path.VOIDEMPO_nonce
                        },
                        success: function (response) {
                            if (response.success && response.data.file_url) {
                                var downloadLink = document.createElement("a");
                                downloadLink.href = response.data.file_url;
                                downloadLink.download = 'Task_report.xls';
                                document.body.appendChild(downloadLink);
                                downloadLink.click();
                                document.body.removeChild(downloadLink);
                            } else {
                                alert("Failed to generate the file.");
                            }
                        },

                        beforeSend: function () {
                            jQuery('.lp-ad-screen').show();
                        },
                        complete: function () {
                            jQuery('.lp-ad-screen').hide();
                        }

                    });
                }
            }, 'pageLength'],
            lengthMenu: [
                [25, 50, 100, 150, 200, 250],
                ['25 rows', '50 rows', '100 rows', '150 rows', '200 rows', '250 rows']
            ],
            pageLength: 25,
            scrollX: true,
            scrollCollapse: true,
            processing: true,
            serverSide: true,
            serverMethod: 'post',
            ajax: {
                url: voidempo_path.ajaxurl + '?action=voidempo_filtertablereportlist',
                method: 'POST',
                data: function (d) {
                    d.from_date = jQuery('#from_date').val();
                    d.to_date = jQuery('#to_date').val();
                    d.project_filter = jQuery('#report_project_filter').val();
                    d.task_filter = jQuery('#report_task_filter').val();
                    d.security = voidempo_path.VOIDEMPO_nonce;
                },
                beforeSend: function () {
                    jQuery('.lp-ad-screen').show();
                },
                complete: function () {
                    jQuery('.lp-ad-screen').hide();
                }
            }
        });


        jQuery('#report_project_filter, #report_task_filter, #from_date, #to_date').change(function () {
            table2.ajax.reload();
        });

        if ($('#voidempo_eod_summary').length > 0) {
            if ($.fn.DataTable.isDataTable('#voidempo_eod_summary')) {
                $('#voidempo_eod_summary').DataTable().clear().destroy();
            }
            jQuery('#voidempo_eod_summary').DataTable({
                "order": [[0, "desc"]],
                "pageLength": 25,
                "lengthMenu": [[25, 50, 100], [25, 50, 100]],
                processing: true,
                serverSide: true,
                serverMethod: 'post',
                ajax: {
                    url: voidempo_path.ajaxurl,
                    type: "POST",
                    data: {
                        action: 'voidempo_filtereodsummary',
                        security: voidempo_path.VOIDEMPO_nonce,
                    },
                    complete: function () {
                        jQuery('.lp-ad-screen').hide();
                    }
                }

            });
        }
        $("#voidempo_eod_date").datepicker({
            maxDate: new Date(),
            dateFormat: 'mm/dd/yy',
            onSelect: function (date) {

                $("#voidempo_eod_date").val(date);

                var post_data = {
                    'date': date,
                    'action': 'voidempo_get_eods_databydate',
                    'security': voidempo_path.VOIDEMPO_nonce,
                };
                $.ajax({
                    url: voidempo_path.ajaxurl,
                    type: 'POST',
                    data: post_data,
                    dataType: 'html',
                    success: function (response) {
                        $(".voidempo_eod_task_div").html(response);

                    },
                    beforeSend: function () {
                        $(".lp-ad-screen").fadeIn();
                    },
                    complete: function () {
                        $(".lp-ad-screen").fadeOut();
                    },
                    error: function (xhr, status, error) {
                        console.log("AJAX Error:", status, error);
                    }
                });

            }

        });
    }
    $(document).off("change", "#from_date, #to_date, #project_filter, #task_filter")
        .on("change", "#from_date, #to_date, #project_filter, #task_filter", function () {

            if ($.fn.DataTable.isDataTable('#voidempo_eod_list_view')) {
                $('#voidempo_eod_list_view').DataTable().ajax.reload();
            }
            if ($.fn.DataTable.isDataTable('#voidempo_project_view')) {
                $('#voidempo_project_view').DataTable().ajax.reload();
            }
        });

    function exportData(action, filename) {
        var fromDate = $('#from_date').val() || '';
        var toDate = $('#to_date').val() || '';
        var projectFilter = $('#project_filter').val() || '';
        var taskFilter = $('#task_filter').val() || '';

        $.ajax({
            url: voidempo_path.ajaxurl,
            type: 'POST',
            data: {
                action: action,
                from_date: fromDate,
                to_date: toDate,
                project_filter: projectFilter,
                task_filter: taskFilter,
                security: voidempo_path.VOIDEMPO_nonce,

            },
            success: function (response) {
                try {
                    var data = JSON.parse(response);
                    if (data.file) {
                        var downloadLink = document.createElement("a");
                        downloadLink.href = data.file;
                        downloadLink.download = filename;
                        document.body.appendChild(downloadLink);
                        downloadLink.click();
                        document.body.removeChild(downloadLink);
                    } else {
                        alert("Export failed. Please try again.");
                    }
                } catch (error) {
                    console.error("Invalid JSON response:", response);
                    alert("Export error. Check console.");
                }
            },
            beforeSend: function () {
                $('.lp-ad-screen').show();
            },
            complete: function () {
                $('.lp-ad-screen').hide();
            }
        });

    }
    jQuery(document).on('change', '#voidempo_task_project', function () {
        var project_id = jQuery(this).val();
        var post_data = {
            'project_id': project_id,
            'action': 'voidempo_check_is_manager',
            'security': voidempo_path.VOIDEMPO_nonce
        };
        jQuery.ajax({
            url: voidempo_path.ajaxurl,
            type: 'POST',
            data: post_data,
            dataType: 'html',
            success: function (response) {
                jQuery('.voidempo_taskc_assign_mem_div').html(response);
                jQuery('#voidempo_taskc_assign_mem').select2({
                    placeholder: '-- Assign Members --',
                    closeOnSelect: false
                });
            }
        });
    });

    window.voidempo_task = {
        voidempo_task_create: function (button) {
            var btn = jQuery(button);
            btn.prop("disabled", true);

            var project_id = jQuery('#voidempo_task_project').val();
            var task_title = jQuery('#voidempo_task_title').val();
            var task_description = jQuery('#voidempo_task_description').val();
            var task_estimated_hours = jQuery('#voidempo_task_estimated_hours').val();
            var voidempo_task_estimated_min = jQuery('#voidempo_task_estimated_min').val();
            var voidempo_taskc_status = jQuery('#voidempo_taskc_status').val();
            var member_ids = jQuery('#voidempo_taskc_assign_mem').val(); // This returns an array

            if (project_id == '0') {
                swal.fire("Please select a project.");
                btn.prop("disabled", false);
                return false;
            }

            if (task_title.trim() === "") {
                swal.fire("Please add the task title.");
                btn.prop("disabled", false);
                return false;
            }

            if (voidempo_task_estimated_min > 59) {
                swal.fire("Minutes should be less than 60");
                btn.prop("disabled", false);
                return false;
            }


            var post_data = {
                'project_id': project_id,
                'task_title': task_title,
                'member_ids': member_ids, // pass the array
                'task_description': task_description,
                'voidempo_taskc_status': voidempo_taskc_status,
                'task_estimated_hours': task_estimated_hours,
                'voidempo_task_estimated_min': voidempo_task_estimated_min,
                'action': 'voidempo_create_task',
                'security': voidempo_path.VOIDEMPO_nonce,
            };

            jQuery.ajax({
                url: voidempo_path.ajaxurl,
                type: 'POST',
                data: post_data,
                dataType: 'html',
                success: function (response) {
                    if (jQuery.trim(response) === 'task_created') {
                        swal.fire("Task Created Successfully");
                        jQuery('#voidempo_task_project').val('');
                        jQuery('#voidempo_task_title').val('');
                        jQuery('#voidempo_task_description').val('');
                        jQuery('#voidempo_task_estimated_hours').val('');
                        jQuery('#voidempo_task_estimated_min').val('');
                        jQuery('#voidempo_taskc_assign_mem').val([]).trigger('change');
                    }
                },
                error: function () {
                    swal.fire("Error creating task. Please try again.");
                },
                beforeSend: function () {
                    $('.lp-ad-screen').show();
                },
                complete: function () {
                    btn.prop("disabled", false);
                }
            });
        }
    };


    jQuery("#voidempo_project_start_date").datepicker();
    jQuery("#voidempo_project_end_date").datepicker();
    jQuery("#voidempo_eod_list_date").datepicker();
    jQuery("#voidempo_eodview_from_date").datepicker();
    jQuery("#voidempo_eodview_to_date").datepicker();
    jQuery(document).on('change', '#myprojfiltersel', function () {
        if (jQuery('#myprojtaskwisefilter').length == 0) {
            var projid = jQuery(this).val();
            if (projid == 0) {
                jQuery('.main_project_div').css('display', 'block');
            } else {
                jQuery('.main_project_div').each(function () {
                    if (jQuery(this).data('projectid') == projid) {
                        jQuery(this).css('display', 'block');
                    } else {
                        jQuery(this).css('display', 'none');
                    }
                });
            }
            if (jQuery('.main_project_div:visible').length == 0) {
                jQuery('.voidempo_eod_submit_but').hide();

            } else {
                jQuery('.voidempo_eod_submit_but').show();
            }
            return false;
        } else {
            selectedfilterval();
        }
    });
    jQuery(document).on('change', '#myprojtaskwisefilter', function () {
        selectedfilterval();
    });

    function selectedfilterval() {
        var thisVal = jQuery('#myprojtaskwisefilter').val();
        var selectedproject = jQuery('#myprojfiltersel').val();
        var currentuserid = jQuery('.addeodcurrentuserid').val();

        if (thisVal == 0 && selectedproject == 0) {
            jQuery('.addeodtaskdiv').show();
            jQuery('.main_project_div').show();
            return false;
        }
        if (thisVal == 0) {
            jQuery('.addeodtaskdiv').each(function () {
                var perpid = jQuery(this).data('projectid');
                if (perpid == selectedproject) {
                    jQuery(this).show();
                    jQuery(this).parent().show();
                } else {
                    jQuery(this).hide();
                    jQuery(this).parent().hide();
                }
            });
        }
        if (thisVal == 1) {
            jQuery('.addeodtaskdiv').each(function () {
                var perpid = jQuery(this).data('projectid');
                if (perpid == selectedproject || selectedproject == 0) {
                    console.log(perpid + '  ' + selectedproject);
                    var taskmember = jQuery(this).data('istaskmember');
                    if (taskmember == 'yes') {
                        jQuery(this).show();
                        jQuery(this).parent().show();
                    } else {
                        jQuery(this).hide();
                    }
                    if (jQuery(this).parent().find('.addeodtaskdiv:visible').length == 0) {
                        jQuery(this).parent().hide();
                    }
                } else {
                    jQuery(this).hide();
                    jQuery(this).parent().hide();
                }
            });
            return false;
        }

        if (thisVal == 2) {
            jQuery('.addeodtaskdiv').each(function () {
                var perpid = jQuery(this).data('projectid');
                if (perpid == selectedproject || selectedproject == 0) {
                    jQuery(this).show();
                    jQuery(this).parent().show();
                    console.log(perpid + '  ' + selectedproject);
                    if (jQuery(this).find('.voidempo_task_mac_members').attr('checked') == 'checked') {
                        jQuery(this).show();
                    } else {
                        jQuery(this).hide();
                    }
                    if (jQuery(this).parent().find('.addeodtaskdiv:visible').length == 0) {
                        jQuery(this).parent().hide();
                    }
                } else {
                    jQuery(this).hide();
                    jQuery(this).parent().hide();
                }
            });
        }
    }
    function initializeTaskDataTable() {
        var projectId = jQuery('.hidprojectid').val();

        if (!projectId) {

            return;
        }

        if ($('#voidempo_task_view_table').length > 0) {
            if ($.fn.DataTable.isDataTable('#voidempo_task_view_table')) {
                $('#voidempo_task_view_table').DataTable().clear().destroy();
            }
            var table5 = jQuery('#voidempo_task_view_table').DataTable({
                columnDefs: [
                    { orderable: true },
                ],
                "pageLength": 25,
                "lengthMenu": [[25, 50, 100], [25, 50, 100]],
                processing: true,
                serverSide: true,
                serverMethod: 'post',
                ajax: {
                    url: voidempo_path.ajaxurl + '?action=voidempo_filtertasklist&project_id=' + jQuery('.hidprojectid').val(),
                    type: "POST",
                    data: function (d) {
                        d.security = voidempo_path.VOIDEMPO_nonce;
                    },
                    complete: function () {
                        jQuery('.lp-ad-screen').hide();
                    }
                }

            });
        }
    }

    jQuery(document).on('ajaxComplete', function (event, xhr, settings) {
        if (settings.data && settings.data.includes('view-task')) {
            initializeTaskDataTable();
        }
    });


    if (window.location.href.includes("view-task")) {
        initializeTaskDataTable();
    }
    jQuery(document).on('change', '#voidempo_task_project1', function () {
        let selectedProjectId = jQuery(this).val();

        let newUrl = updateQueryStringParameter(window.location.href, 'project_id', selectedProjectId);
        history.pushState(null, "", newUrl);

        initializeTaskDataTable(selectedProjectId);
        location.reload();
    });

    function updateQueryStringParameter(uri, key, value) {
        let re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        let separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re)) {
            return uri.replace(re, '$1' + key + "=" + value + '$2');
        } else {
            return uri + separator + key + "=" + value;
        }
    }

    loadTableData();

    jQuery(document).on("click", "#add-project-btn", function (e) {

        e.preventDefault();
        jQuery('.error').text('');
        var isValid = true;
        var projectTitle = jQuery('#project_title').val();
        var projectDescription = jQuery('#project_description').val();
        var startdate = jQuery('#voidempo_project_start_date').val();
        var enddate = jQuery('#voidempo_project_end_date').val();
        var projectmanager = jQuery('#voidempo_project_manager').val();
        var projectmembers = jQuery('#voidempo_project_members').val() || [];

        var projectstatus = jQuery('#voidempo_project_status').val();
        if (!projectTitle) {
            jQuery('#error_project_title').text('Project title is required.');
            isValid = false;
        }
        if (!isValid) return;
        jQuery.ajax({
            type: 'POST',
            url: voidempo_path.ajaxurl,
            data: {
                action: 'voidempo_add_project_ajax',
                project_title: projectTitle,
                project_description: projectDescription,
                voidempo_project_start_date: startdate,
                voidempo_project_end_date: enddate,
                voidempo_project_manager: projectmanager,
                voidempo_project_members: projectmembers,
                voidempo_project_status: projectstatus,
                security: voidempo_path.VOIDEMPO_nonce
            },
            dataType: 'json',
            success: function (response) {
                jQuery('#project-message').text(response.message);
                if (response.success) {
                     jQuery('#add-project-form')[0].reset();
                     alert("Project Added Successfully!");
                    if (jQuery('#project-list-table').length > 0 && jQuery.fn.DataTable.isDataTable('#project-list-table')) {
                        jQuery('#project-list-table').DataTable().ajax.reload(null, false); 
                    }
                }
            },
            error: function () {
                jQuery('#project-message').text('An error occurred.');
            }
        });
    });

    jQuery(document).on('click', '.edit-project', function () {

        const projectID = jQuery(this).data('id');

        jQuery.ajax({
            url: voidempo_path.ajaxurl,
            type: 'POST',
            data: {
                action: 'voidempo_get_single_project',
                project_id: projectID,
                security: voidempo_path.VOIDEMPO_nonce
            },
            success: function (res) {
                if (res.success) {
                    const p = res.data;
                    jQuery('#edit_project_id').val(p.id);
                    jQuery('#edit_project_title').val(p.project_title);
                    jQuery('#edit_status').val(p.status);
                    jQuery('#edit_start_date').val(p.start_date);
                    jQuery('#edit_end_date').val(p.end_date);
                    jQuery('#edit_manager').html(p.managers_dropdown);
                    jQuery('#edit_members').html(p.members_dropdown).select2({
                        dropdownParent: jQuery('#editProjectModal'),
                        width: '100%'
                    });

                    jQuery('#editProjectModal').modal('show');
                } else {
                    alert(res.data.message || 'Error fetching project data.');
                }
            }
        });
    });
    jQuery(document).on("submit", "#editProjectForm", function (e) {

        e.preventDefault();
        const formData = jQuery(this).serialize();

        jQuery.ajax({
            url: voidempo_path.ajaxurl,
            type: 'POST',
            data: {
                action: 'voidempo_update_project',
                data: formData,
                security: voidempo_path.VOIDEMPO_nonce
            },
            success: function (res) {
                if (res.success) {
                    alert('Project updated successfully.');
                    jQuery('#editProjectModal').modal('hide');
                    jQuery('#project-list-table').DataTable().ajax.reload();
                } else {
                    alert(res.data.message || 'Update failed.');
                }
            }
        });
    });
    // Delete project
    jQuery(document).on('click', '.delete-project', function () {
        const projectID = $(this).data('id');
        if (!confirm('Are you sure you want to delete this project?')) return;

        jQuery.ajax({
            url: voidempo_path.ajaxurl,
            type: 'POST',
            data: {
                action: 'voidempo_delete_project',
                project_id: projectID,
                security: voidempo_path.VOIDEMPO_nonce,
            },
            success: function (res) {
                if (res.success) {
                    jQuery('#project-list-table').DataTable().ajax.reload();
                } else {
                    alert(res.data.message || 'Failed to delete project.');
                }
            }
        });
    });


    jQuery(document).on("click", "#btn_user", function (e) {
        e.preventDefault();
        jQuery('.error').text('');

        var isValid = true;
        var username = jQuery('#username').val().trim();
        var email = jQuery('#email').val().trim();
        var password = jQuery('#password').val().trim();
        var first_name = jQuery('#first_name').val().trim();
        var last_name = jQuery('#last_name').val().trim();
        var formData = {
            username: jQuery('#username').val(),
            email: jQuery('#email').val(),
            password: jQuery('#password').val(),
            first_name: jQuery('#first_name').val(),
            last_name: jQuery('#last_name').val(),
            user_dob: jQuery('#user_dob').val(),
            user_joining_date: jQuery('#user_joining_date').val(),
            //Additional Fields.
            user_starting_salary: jQuery('#user_starting_salary').val(),
            user_end_of_probation: jQuery('#user_end_of_probation').val(),
            marital_status  :  jQuery('input[name="marital_status"]:checked').val(),
            user_marriage_anniversary : jQuery('#user_marriage_anniversary').val(),
            spouse_name : jQuery('#spouse_name').val(),
            spouse_birthday: jQuery('#spouse_birthday').val(),
            child1_name: jQuery('#child1_name').val(),
            child1_birthday: jQuery('#child1_birthday').val(),
            child2_name: jQuery('#child2_name').val(),
            child2_birthday: jQuery('#child2_birthday').val(),
            leave_year: jQuery('#leave_year').val(),
            leave_count: jQuery('#leave_count').val(),
            leave_count_basis: jQuery('input[name="leave_count_basis"]:checked').val(),
        };
        if (!username) {
            jQuery('#error_username').text('Username is required.');
            isValid = false;
        }

        if (!email) {
            jQuery('#error_email').text('Email is required.');
            isValid = false;
        } else if (!/^\S+@\S+\.\S+$/.test(email)) {
            jQuery('#error_email').text('Enter a valid email.');
            isValid = false;
        }

        if (!password) {
            jQuery('#error_password').text('Password is required.');
            isValid = false;
        }

        if (!first_name) {
            jQuery('#error_first_name').text('First name is required.');
            isValid = false;
        }

        if (!last_name) {
            jQuery('#error_last_name').text('Last name is required.');
            isValid = false;
        }

        if (!isValid) return;
        jQuery.ajax({
            url: voidempo_path.ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'voidempo_user_registration',
                form_data: jQuery.param(formData),
                security: voidempo_path.VOIDEMPO_nonce,
            },
            success: function (response) {
                jQuery('#ajax-registration-result').html(response.message);
                if (response.success) {
                    jQuery('#registration-form')[0].reset();
                    alert("User registered successfully!");
                    if (jQuery('#userTable').length > 0 && jQuery.fn.DataTable.isDataTable('#userTable')) {
                            jQuery('#userTable').DataTable().ajax.reload(null, false); // false keeps current pagination
                    }
                }
                else {
                    if (response.message.includes('Username')) {
                        jQuery('#error_username').html(response.message);
                    } else if (response.message.includes('Email')) {
                        jQuery('#error_email').html(response.message);
                    } else {
                        jQuery('#general_error').html(response.message);
                    }
                }
            }
        });
    });

    jQuery(document).on('click', '.edit-user', function () {
        const userId = jQuery(this).data('id');

        jQuery.ajax({
            url: voidempo_path.ajaxurl,
            type: 'POST',
            data: {
                action: 'voidempo_get_user_details',
                user_id: userId,
                security: voidempo_path.VOIDEMPO_nonce,
            },
            success: function (res) {
                if (res.success) {
                    const data = res.data;
                    jQuery('#edit_user_id').val(userId);
                    jQuery('#edit_user_name').val(data.name);
                    jQuery('#edit_user_dob').val(data.dob);
                    jQuery('#edit_user_joining').val(data.joining);
                    jQuery('#edit_user_salary').val(data.salary);
                    jQuery('#edit_user_Probation').val(data.Probation);
                    jQuery('#edit_leave_year').val(data.leave_year);
                    jQuery('#Leave_count').val(data.Leave_count);
                    jQuery('#edit_user_Anniversary').val(data.user_Anniversary);
                    jQuery('#edit_spouse_name').val(data.spouse_name);
                    jQuery('#edit_Spouse_birthday').val(data.Spouse_birthday);
                    jQuery('#edit_Child1_name').val(data.Child1_name);
                    jQuery('#edit_Child1_birthday').val(data.Child1_birthday);
                    jQuery('#edit_Child2_name').val(data.Child2_name);
                    jQuery('#edit_Child2_birthday').val(data.Child2_birthday);
                    if (data.Leave_Basis === 'joining_date') {
                        jQuery('#leave_basis_joining').prop('checked', true);
                    } else if (data.Leave_Basis === 'probation_end') {
                        jQuery('#leave_basis_probation').prop('checked', true);
                    }

                    if (data.marital_status === 'married') {
                        jQuery('#marital_status_married').prop('checked', true);
                    } else if (data.marital_status === 'unmarried') {
                        jQuery('#marital_status_unmarried').prop('checked', true);
                    }
                    if (data.disabled == 1) {
                        jQuery('#status_deactive').prop('checked', true);
                    } else {
                        jQuery('#status_active').prop('checked', true);
                    }
                    jQuery('#editUserModal').modal('show');
                }
            },
             error: function (xhr, status, error) {
        console.error("AJAX Error:", status, error);
    }
        });
    });

    jQuery(document).on('click', '.update_user_btn', function (e) {
        e.preventDefault();
        const userId = jQuery('#edit_user_id').val();

        const leave_years = jQuery('#edit_leave_year').val();
        const leave_counts = jQuery('#Leave_count').val();

        const formData = {
            action: 'voidempo_update_user_details',
            user_id: userId,
            dob: jQuery('#edit_user_dob').val(),
            joining: jQuery('#edit_user_joining').val(),
            //Additiona.
            salary: jQuery('#edit_user_salary').val(),
            probation: jQuery('#edit_user_Probation').val(),
            marital_status: jQuery('input[name="edit_marital_status"]:checked').val(),
            user_Anniversary : jQuery('#edit_user_Anniversary').val(),
            spouse_name : jQuery('#edit_spouse_name').val(),
            spouse_birthday :jQuery('#edit_Spouse_birthday').val(),
            Child1_name :jQuery( '#edit_Child1_name').val(),
            Child1_birthday:jQuery('#edit_Child1_birthday').val(),
            child2_name : jQuery('#edit_Child2_name').val(),
            child2_birthday : jQuery('#edit_Child2_birthday').val(),
            leave_basis_option: jQuery('input[name="leave_basis_option"]:checked').val(),
            leave_year: leave_years,
            leave_count: leave_counts,
            employee_status: jQuery('input[name="employee_status"]:checked').val(),
            security: voidempo_path.VOIDEMPO_nonce,
        };

        jQuery.ajax({
            url: voidempo_path.ajaxurl,
            type: 'POST',
            data: formData,
            success: function (res) {
                if (res.success) {
                    alert('User data updated successfully!');
                    jQuery('#editUserModal').modal('hide');
                      if (jQuery('#userTable').length > 0 && jQuery.fn.DataTable.isDataTable('#userTable')) {
                            jQuery('#userTable').DataTable().ajax.reload(null, false); // false keeps current pagination
                        }
                } else {
                    alert('Something went wrong!');
                }
            }
        });
    });

    jQuery(document).on('click', '.delete-user', function () {
        const userId = jQuery(this).data('id');

        if (confirm('Are you sure you want to delete this user\'s details?')) {
            jQuery.ajax({
                url: voidempo_path.ajaxurl,
                type: 'POST',
                data: {
                    action: 'voidempo_delete_user_details',
                    user_id: userId,
                    security: voidempo_path.VOIDEMPO_nonce,
                },
                success: function (res) {
                    if (res.success) {
                        alert(res.data.message);
                        if (jQuery('#userTable').length > 0 && jQuery.fn.DataTable.isDataTable('#userTable')) {
                            jQuery('#userTable').DataTable().ajax.reload(null, false); // false keeps current pagination
                        }
                    } else {
                        alert('Failed to delete user details.');
                    }
                }
            });
        }
    });

    jQuery(document).on('click', '.voidempo_delete_eod_but', function () {
        var eod_id = jQuery(this).data('eod_id');
        var user_id = jQuery(this).data('user_id');
        var project_id = jQuery(this).data('project_id');
        var task_id = jQuery(this).data('task_id');
        var post_data = {
            'eod_id': eod_id,
            'user_id': user_id,
            'project_id': project_id,
            'task_id': task_id,
            'action': 'voidempo_delete_eod',
            'security': voidempo_path.VOIDEMPO_nonce,
        };
        swal.fire({
              title: "Are you sure?",
                text: "You will not be able to recover this EOD!",
                icon: "warning", 
                showCancelButton: true,
                confirmButtonText: "Yes, delete it!",
                cancelButtonText: "Cancel",
                customClass: {
                    confirmButton: "btn btn-danger", 
                    cancelButton: "btn btn-secondary"
                },
                reverseButtons: true 
       }).then((result) => {
            if (result.isConfirmed) {
                jQuery.ajax({
                    url: voidempo_path.ajaxurl,
                    type: 'POST',
                    data: post_data,
                    dataType: 'html',
                    success: function (response) {
                        if (response === 'Deleted') {
                            Swal.fire({
                                title: "Deleted!",
                                text: "Your EOD file has been deleted.",
                                icon: "success",
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: "btn btn-success"
                                }
                            }).then(() => {
                                    if ($.fn.DataTable.isDataTable('#voidempo_eod_list_view ')) {
                                    jQuery('#voidempo_eod_list_view ').DataTable().ajax.reload(null, false); 
                                    }                            
                                });
                        } else {

                            if ($.fn.DataTable.isDataTable('#voidempo_eod_list_view ')) {
                                    jQuery('#voidempo_eod_list_view ').DataTable().ajax.reload(null, false); 
                            }   
                        }
                    }
                });
            }
        });
    });

    
    jQuery(document).on("click", ".voidempo_eod_submit_but", function (e) {
        e.preventDefault();
        var eodDate = jQuery("#voidempo_eod_date").val().trim();
        var eodData = {};

         jQuery(".voidempo_eod_hours_all").each(function () {
            var hours = jQuery(this).val();
            if (hours === "" || hours === "00:00") {
                var taskDiv = jQuery(this).closest(".addeodtaskdiv");
                taskDiv.remove();
            }
        });

        jQuery(".addeodtaskdiv").each(function () {
            var projectID = jQuery(this).data("projectid");
            var taskID = jQuery(this).data("task_id");
            var hoursElement = jQuery(this).find(".voidempo_eod_hours_all");
            var notesElement = jQuery(this).find("#voidempo_task_note");
            var hours = hoursElement.length ? hoursElement.val().trim() : "";
            var notes = notesElement.length ? notesElement.val().trim() : "";
            var markAsComplete = jQuery(this).find(".mark-as-complete").is(":checked") ? "on" : "";


            if (hours !== "" || notes !== "") {
                if (!eodData[projectID]) {
                    eodData[projectID] = {};
                }
                eodData[projectID][taskID] = {
                    eod_hours: hours,
                    eod_notes: notes,
                    mark_as_complete: markAsComplete
                };
            }
        });


        if (jQuery.isEmptyObject(eodData)) {
            jQuery("#eod_status").html('<div class="alert alert-warning">Please enter EOD details before submitting.</div>');
            return;
        }

        jQuery.ajax({
            url: voidempo_path.ajaxurl,
            type: "POST",
            data: {
                action: "voidempo_insert_eod_data",
                eod_date: eodDate,
                eodData:  eodData,
                security: voidempo_path.VOIDEMPO_nonce
            },
            dataType: "json",
            beforeSend: function () {
                jQuery(".voidempo_eod_submit_but").prop("disabled", true).text("Submitting...");

            },
            success: function (response) {
                if (response.success) {
                    alert("Eod Submitted Successfully");
                    jQuery(".voidempo_eod_hours_all, #voidempo_task_note").val("");
                    jQuery(".mark-as-complete").prop("checked", false);
                    location.reload();
                } else {
                    jQuery("#eod_status").html('<div class="alert alert-danger">' + response.data.message + '</div>');
                }
            },
            error: function (xhr, status, error) {
                console.error("AJAX Error:", xhr.responseText);
                jQuery("#eod_status").html('<div class="alert alert-danger">Error submitting EOD. Please try again.</div>');
            },
            complete: function () {
                jQuery(".voidempo_eod_submit_but").prop("disabled", false).text("Submit EOD");
            }
        });
    });

        

});

