/**
 * Daterangepicker Monday Override
 * Forces all daterangepicker instances to start from Monday
 */

(function() {
    'use strict';
    
    // Wait for jQuery and moment to be available
    if (typeof $ === 'undefined' || typeof moment === 'undefined') {
        setTimeout(arguments.callee, 100);
        return;
    }
    
    // Override moment.js global locale to start week from Monday
    if (moment && moment.updateLocale) {
        moment.updateLocale('en', {
            week: {
                dow: 1 // Monday is the first day of the week
            }
        });
    }
    
    // Override the original daterangepicker function if it exists
    if ($ && $.fn.daterangepicker) {
        var originalDaterangepicker = $.fn.daterangepicker;
        
        $.fn.daterangepicker = function(options, callback) {
            // Ensure options object exists
            options = options || {};
            
            // Force locale settings
            options.locale = options.locale || {};
            options.locale.firstDay = 1; // Monday = 1, Sunday = 0
            
            // Set correct day of week labels starting with Monday
            options.locale.daysOfWeek = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
            
            // Call the original function with modified options
            return originalDaterangepicker.call(this, options, callback);
        };
        
        // Copy over any static properties/methods
        for (var prop in originalDaterangepicker) {
            if (originalDaterangepicker.hasOwnProperty(prop)) {
                $.fn.daterangepicker[prop] = originalDaterangepicker[prop];
            }
        }
    }
    
    // Also override for any existing daterangepicker instances
    $(document).ready(function() {
        // Force update any existing daterangepicker instances
        $('.daterangepicker').each(function() {
            var $this = $(this);
            if ($this.data('daterangepicker')) {
                var drp = $this.data('daterangepicker');
                if (drp && drp.locale) {
                    drp.locale.firstDay = 1;
                    drp.locale.daysOfWeek = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
                    if (drp.updateCalendars) {
                        drp.updateCalendars();
                    }
                }
            }
        });
        
        // Also force any input elements with ng-daterangepicker
        $('[ng-daterangepicker], [data-ranges]').each(function() {
            var $this = $(this);
            setTimeout(function() {
                if ($this.data('daterangepicker')) {
                    var drp = $this.data('daterangepicker');
                    if (drp && drp.locale) {
                        drp.locale.firstDay = 1;
                        drp.locale.daysOfWeek = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
                        if (drp.updateCalendars) {
                            drp.updateCalendars();
                        }
                    }
                }
            }, 500);
        });
        
        // Watch for dynamically created daterangepickers
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.addedNodes) {
                    $(mutation.addedNodes).find('.daterangepicker').each(function() {
                        var $this = $(this);
                        if ($this.data('daterangepicker')) {
                            var drp = $this.data('daterangepicker');
                            if (drp && drp.locale) {
                                drp.locale.firstDay = 1;
                                drp.locale.daysOfWeek = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
                                if (drp.updateCalendars) {
                                    drp.updateCalendars();
                                }
                            }
                        }
                    });
                }
            });
        });
        
        observer.observe(document.body, { childList: true, subtree: true });
        
        // Handle HTML5 date inputs (like holiday request date picker)
        function setHtml5DateLocale() {
            // Try to set the browser locale to use Monday as first day
            if (document.documentElement) {
                // Set lang attribute to enforce Monday start
                document.documentElement.setAttribute('lang', 'en-GB'); // UK locale starts week on Monday
            }
            
            // Add CSS to override date input calendar appearance if possible
            var style = document.createElement('style');
            style.textContent = `
                /* Force Monday start for HTML5 date inputs where possible */
                input[type="date"]::-webkit-calendar-picker-indicator {
                    /* Browser-specific styling can go here */
                }
            `;
            document.head.appendChild(style);
        }
        
        // Apply HTML5 date locale settings
        setHtml5DateLocale();
        
        // Also handle any future HTML5 date inputs
        $(document).on('focus', 'input[type="date"]', function() {
            // When a date input is focused, ensure locale is set
            if (this.lang !== 'en-GB') {
                this.lang = 'en-GB';
            }
        });
        
        // Aggressive replacement of HTML5 date inputs
        function aggressivelyReplaceHtml5DateInputs() {
            $('input[type="date"]').each(function() {
                var $input = $(this);
                
                // Don't replace if already processed
                if ($input.hasClass('date-override-processed')) {
                    return;
                }
                
                $input.addClass('date-override-processed');
                
                // Store original attributes
                var originalClass = $input.attr('class') || '';
                var originalStyle = $input.attr('style') || '';
                var originalNgModel = $input.attr('ng-model') || '';
                var originalNgChange = $input.attr('ng-change') || '';
                var originalMin = $input.attr('min') || '';
                var originalMax = $input.attr('max') || '';
                var originalValue = $input.val() || '';
                
                // Remove the type="date" to disable native behavior
                $input.attr('type', 'text');
                $input.attr('readonly', 'readonly');
                $input.css('cursor', 'pointer');
                
                // Add calendar icon if it doesn't exist
                if (!$input.next('.calendar-icon').length) {
                    // Wrap input in a container for proper positioning
                    $input.wrap('<div style="position: relative; display: inline-block; width: 100%;"></div>');
                    
                    // Add calendar icon that matches the original HTML5 date input style
                    var $icon = $('<i class="fa fa-calendar calendar-icon" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); pointer-events: none; color: #999; font-size: 16px; z-index: 1;"></i>');
                    $input.after($icon);
                    
                    // Adjust input padding to make room for icon
                    $input.css({
                        'padding-right': '40px',
                        'background': 'white'
                    });
                }
                
                // Add click handler to show custom calendar
                $input.off('click.datepicker').on('click.datepicker', function(e) {
                    e.preventDefault();
                    showCustomCalendar($input);
                });
                
                // Also add click handler to the icon's parent container
                $input.parent().off('click.datepicker-container').on('click.datepicker-container', function(e) {
                    if ($(e.target).hasClass('calendar-icon') || $(e.target).is($input)) {
                        e.preventDefault();
                        showCustomCalendar($input);
                    }
                });
            });
        }
        
        // Custom calendar popup function
        function showCustomCalendar($input) {
            // Remove any existing calendar
            $('.custom-calendar-popup').remove();
            
            var currentDate = new Date();
            var selectedDate = $input.val() ? new Date($input.val()) : null;
            
            // Create calendar HTML
            var calendarHtml = '<div class="custom-calendar-popup" style="position: absolute; z-index: 9999; background: white; border: 1px solid #ccc; border-radius: 4px; padding: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">' +
                '<div class="calendar-header" style="text-align: center; margin-bottom: 10px; font-weight: bold;">' +
                '<button type="button" class="prev-month" style="float: left; background: none; border: none; cursor: pointer;">&lt;</button>' +
                '<span class="current-month-year"></span>' +
                '<button type="button" class="next-month" style="float: right; background: none; border: none; cursor: pointer;">&gt;</button>' +
                '</div>' +
                '<table class="calendar-table" style="border-collapse: collapse; width: 100%;">' +
                '<thead><tr style="background: #f5f5f5;"><th style="padding: 5px; text-align: center; font-size: 12px;">Mo</th><th style="padding: 5px; text-align: center; font-size: 12px;">Tu</th><th style="padding: 5px; text-align: center; font-size: 12px;">We</th><th style="padding: 5px; text-align: center; font-size: 12px;">Th</th><th style="padding: 5px; text-align: center; font-size: 12px;">Fr</th><th style="padding: 5px; text-align: center; font-size: 12px;">Sa</th><th style="padding: 5px; text-align: center; font-size: 12px;">Su</th></tr></thead>' +
                '<tbody class="calendar-body"></tbody>' +
                '</table>' +
                '<div style="text-align: center; margin-top: 10px;"><button type="button" class="calendar-close" style="background: #ddd; border: none; padding: 5px 15px; border-radius: 3px; cursor: pointer;">Close</button></div>' +
                '</div>';
            
            var $calendar = $(calendarHtml);
            
            // Position calendar near input
            var inputOffset = $input.offset();
            $calendar.css({
                top: inputOffset.top + $input.outerHeight() + 5,
                left: inputOffset.left
            });
            
            $('body').append($calendar);
            
            // Generate calendar
            function generateCalendar(year, month) {
                var firstDay = new Date(year, month, 1);
                var lastDay = new Date(year, month + 1, 0);
                var startDate = new Date(firstDay);
                
                // Adjust to Monday start (1 = Tuesday, so we want 1)
                var dayOfWeek = firstDay.getDay();
                var offset = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // Convert Sunday=0 to Sunday=6
                startDate.setDate(firstDay.getDate() - offset);
                
                var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                $calendar.find('.current-month-year').text(monthNames[month] + ' ' + year);
                
                var $tbody = $calendar.find('.calendar-body');
                $tbody.empty();
                
                var currentDate = new Date(startDate);
                for (var week = 0; week < 6; week++) {
                    var $row = $('<tr></tr>');
                    for (var day = 0; day < 7; day++) {
                        var $cell = $('<td style="padding: 5px; text-align: center; cursor: pointer; border: 1px solid #eee;"></td>');
                        var cellDate = new Date(currentDate);
                        
                        $cell.text(currentDate.getDate());
                        $cell.data('date', currentDate.getFullYear() + '-' + 
                                  String(currentDate.getMonth() + 1).padStart(2, '0') + '-' + 
                                  String(currentDate.getDate()).padStart(2, '0'));
                        
                        if (currentDate.getMonth() !== month) {
                            $cell.css('color', '#ccc');
                        }
                        
                        if (selectedDate && currentDate.toDateString() === selectedDate.toDateString()) {
                            $cell.css('background-color', '#337ab7').css('color', 'white');
                        }
                        
                        $cell.on('click', function() {
                            var dateValue = $(this).data('date');
                            $input.val(dateValue);
                            $input.trigger('change');
                            if ($input.attr('ng-change')) {
                                $input.scope().$eval($input.attr('ng-change'));
                                $input.scope().$apply();
                            }
                            $calendar.remove();
                        });
                        
                        $row.append($cell);
                        currentDate.setDate(currentDate.getDate() + 1);
                    }
                    $tbody.append($row);
                }
            }
            
            generateCalendar(currentDate.getFullYear(), currentDate.getMonth());
            
            // Navigation
            $calendar.find('.prev-month').on('click', function() {
                currentDate.setMonth(currentDate.getMonth() - 1);
                generateCalendar(currentDate.getFullYear(), currentDate.getMonth());
            });
            
            $calendar.find('.next-month').on('click', function() {
                currentDate.setMonth(currentDate.getMonth() + 1);
                generateCalendar(currentDate.getFullYear(), currentDate.getMonth());
            });
            
            $calendar.find('.calendar-close').on('click', function() {
                $calendar.remove();
            });
            
            // Close on outside click
            $(document).on('click.calendar', function(e) {
                if (!$(e.target).closest('.custom-calendar-popup').length && !$(e.target).is($input)) {
                    $calendar.remove();
                    $(document).off('click.calendar');
                }
            });
        }
        
        // Force update Angular daterangepicker elements
        function forceUpdateAngularDaterangepickers() {
            // Find elements with ng-daterangepicker
            $('[ng-daterangepicker], [data-ng-daterangepicker]').each(function() {
                var $element = $(this);
                console.log('Found ng-daterangepicker element:', $element[0]);
                
                // Try to access the daterangepicker instance
                setTimeout(function() {
                    if ($element.data('daterangepicker')) {
                        var drp = $element.data('daterangepicker');
                        console.log('Found daterangepicker instance, updating locale...');
                        
                        if (drp.locale) {
                            drp.locale.firstDay = 1;
                            drp.locale.daysOfWeek = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
                            
                            // Force redraw
                            if (drp.updateCalendars) {
                                drp.updateCalendars();
                            }
                            if (drp.render) {
                                drp.render();
                            }
                            console.log('Updated daterangepicker locale to start from Monday');
                        }
                    }
                }, 200);
                
                // Also try clicking to force initialization and then update
                setTimeout(function() {
                    if (!$element.data('daterangepicker')) {
                        console.log('Triggering click to initialize daterangepicker...');
                        $element.trigger('click');
                        
                        setTimeout(function() {
                            if ($element.data('daterangepicker')) {
                                var drp = $element.data('daterangepicker');
                                if (drp.locale) {
                                    drp.locale.firstDay = 1;
                                    drp.locale.daysOfWeek = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
                                    if (drp.updateCalendars) {
                                        drp.updateCalendars();
                                    }
                                    console.log('Force-initialized and updated daterangepicker');
                                }
                                // Close it after updating
                                if (drp.hide) {
                                    drp.hide();
                                }
                            }
                        }, 100);
                    }
                }, 500);
            });
        }
        
        // Apply to existing inputs immediately
        aggressivelyReplaceHtml5DateInputs();
        
        // Also check for Angular daterangepickers immediately
        forceUpdateAngularDaterangepickers();
        
        // Apply multiple times to catch dynamically loaded content
        setTimeout(function() {
            console.log('Running delayed HTML5 date input replacement...');
            aggressivelyReplaceHtml5DateInputs();
            forceUpdateAngularDaterangepickers();
        }, 500);
        
        setTimeout(function() {
            console.log('Running second delayed HTML5 date input replacement...');
            aggressivelyReplaceHtml5DateInputs();
            forceUpdateAngularDaterangepickers();
        }, 2000);
        
        setTimeout(function() {
            console.log('Running third delayed HTML5 date input replacement...');
            aggressivelyReplaceHtml5DateInputs();
            forceUpdateAngularDaterangepickers();
        }, 5000);
        
        // Watch for modal openings and new content
        $(document).on('shown.bs.modal', function() {
            console.log('Modal opened, checking for HTML5 date inputs...');
            setTimeout(aggressivelyReplaceHtml5DateInputs, 100);
            setTimeout(aggressivelyReplaceHtml5DateInputs, 500);
            
            // Also force update any ng-daterangepicker elements in modals
            setTimeout(function() {
                console.log('Checking for ng-daterangepicker elements in modal...');
                forceUpdateAngularDaterangepickers();
            }, 100);
        });
        
        // Also watch for any content changes
        if (window.MutationObserver) {
            var contentObserver = new MutationObserver(function(mutations) {
                var shouldCheck = false;
                mutations.forEach(function(mutation) {
                    if (mutation.addedNodes.length > 0) {
                        for (var i = 0; i < mutation.addedNodes.length; i++) {
                            var node = mutation.addedNodes[i];
                            if (node.nodeType === 1) { // Element node
                                if (node.querySelector && node.querySelector('input[type="date"]')) {
                                    shouldCheck = true;
                                    break;
                                }
                                if (node.tagName === 'INPUT' && node.type === 'date') {
                                    shouldCheck = true;
                                    break;
                                }
                            }
                        }
                    }
                });
                
                if (shouldCheck) {
                    console.log('New HTML5 date inputs detected, processing...');
                    setTimeout(aggressivelyReplaceHtml5DateInputs, 100);
                }
            });
            
            contentObserver.observe(document.body, { 
                childList: true, 
                subtree: true 
            });
        }
    });
    
})();

console.log('Daterangepicker Monday Override loaded - all calendars will start from Monday');
console.log('Checking for HTML5 date inputs on page...');

// Debug: Check what date inputs exist
$(document).ready(function() {
    console.log('Found HTML5 date inputs:', $('input[type="date"]').length);
    $('input[type="date"]').each(function(i) {
        console.log('Date input ' + i + ':', this);
    });
});