// Toggle sidebar
document.addEventListener('DOMContentLoaded', function() {
    // -----------------------------------------------------------------
    // 1. Sidebar Toggle Functionality
    // -----------------------------------------------------------------
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebar = document.getElementById('sidebar-wrapper');
    
    if(sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            const currentMargin = sidebar.style.marginLeft || getComputedStyle(sidebar).marginLeft;
            
            if(currentMargin === '0px' || currentMargin === '' || currentMargin === '0') {
                sidebar.style.marginLeft = '-250px';
            } else {
                sidebar.style.marginLeft = '0px';
            }
        });
    }

    // -----------------------------------------------------------------
    // 2. Real-time Clock
    // -----------------------------------------------------------------
    function updateClock() {
        const clockElement = document.getElementById('liveClock');
        if(clockElement) {
            const now = new Date();
            clockElement.textContent = now.toLocaleTimeString();
        }
    }
    setInterval(updateClock, 1000);
    updateClock();

    // -----------------------------------------------------------------
    // 3. Attendance Clock In/Out
    // -----------------------------------------------------------------
    const clockBtn = document.getElementById('clockBtn');
    if(clockBtn) {
        clockBtn.addEventListener('click', function() {
            const currentTime = new Date().toLocaleTimeString();
            const status = this.textContent.includes('In') ? 'clocked_in' : 'clocked_out';
            
            fetch('modules/attendance/clock.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    time: currentTime,
                    status: status
                })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if(data.success) {
                    location.reload();
                }
            });
        });
    }

    // -----------------------------------------------------------------
    // 4. Leave Application Form Validation
    // -----------------------------------------------------------------
    const leaveForm = document.getElementById('leaveForm');
    if(leaveForm) {
        leaveForm.addEventListener('submit', function(e) {
            const startDate = new Date(document.getElementById('start_date').value);
            const endDate = new Date(document.getElementById('end_date').value);
            
            if(startDate > endDate) {
                e.preventDefault();
                alert('End date must be after start date!');
            }
        });
    }

    // -----------------------------------------------------------------
    // 5. Leave Days Calculator
    // -----------------------------------------------------------------
    function initLeaveCalculator() {
        const startDate = document.querySelector('input[name="start_date"]');
        const endDate = document.querySelector('input[name="end_date"]');
        const daysCount = document.getElementById('days_count');
        
        if(startDate && endDate && daysCount) {
            function calculateDays() {
                if(startDate.value && endDate.value) {
                    const start = new Date(startDate.value);
                    const end = new Date(endDate.value);
                    
                    if(start > end) {
                        daysCount.value = 'Invalid dates';
                        return;
                    }
                    
                    // Calculate difference in days
                    const diffTime = end.getTime() - start.getTime();
                    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
                    daysCount.value = diffDays + ' day(s)';
                }
            }
            
            startDate.addEventListener('change', calculateDays);
            endDate.addEventListener('change', calculateDays);
            
            // Initial calculation if dates are pre-filled
            calculateDays();
        }
    }
    initLeaveCalculator();

    // -----------------------------------------------------------------
    // 6. Intern Management Functions
    // -----------------------------------------------------------------
    function initInternManagement() {
        // Auto-calculate intern duration
        const startDate = document.querySelector('input[name="start_date"]');
        const endDate = document.querySelector('input[name="end_date"]');
        
        if(startDate && endDate) {
            function calculateDuration() {
                if(startDate.value && endDate.value) {
                    const start = new Date(startDate.value);
                    const end = new Date(endDate.value);
                    const duration = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;
                    
                    // Show warning if duration is too short or too long
                    const durationElement = document.getElementById('durationDisplay');
                    if(durationElement) {
                        durationElement.textContent = duration + ' days';
                        
                        if(duration < 30) {
                            durationElement.className = 'text-warning';
                        } else if(duration > 180) {
                            durationElement.className = 'text-danger';
                        } else {
                            durationElement.className = 'text-success';
                        }
                    }
                }
            }
            
            startDate.addEventListener('change', calculateDuration);
            endDate.addEventListener('change', calculateDuration);
        }
        
        // Checklist functionality
        const checklistItems = document.querySelectorAll('.checklist-item');
        checklistItems.forEach(item => {
            item.addEventListener('click', function() {
                this.classList.toggle('completed');
            });
        });
        
        // Print functionality
        const printBtn = document.getElementById('printInternsBtn');
        if(printBtn) {
            printBtn.addEventListener('click', function() {
                const printContent = document.querySelector('.card').innerHTML;
                const originalContent = document.body.innerHTML;
                
                document.body.innerHTML = `
                    <html>
                        <head>
                            <title>Intern Report</title>
                            <style>
                                body { font-family: Arial, sans-serif; }
                                table { width: 100%; border-collapse: collapse; }
                                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                                th { background-color: #f2f2f2; }
                                .header { text-align: center; margin-bottom: 20px; }
                            </style>
                        </head>
                        <body>
                            <div class="header">
                                <h2>Intern Management Report</h2>
                                <p>Generated on: ${new Date().toLocaleDateString()}</p>
                            </div>
                            ${printContent}
                            <script>
                                window.print();
                                setTimeout(() => {
                                    document.body.innerHTML = originalContent;
                                    location.reload();
                                }, 1000);
                            <\/script>
                        </body>
                    </html>
                `;
            });
        }
    }
    // Call the function
    initInternManagement();

    // -----------------------------------------------------------------
    // 7. Reports Module Functions
    // -----------------------------------------------------------------
    function initReports() {
        // Date range picker for leave reports
        const startDate = document.querySelector('input[name="start_date"]');
        const endDate = document.querySelector('input[name="end_date"]');
        
        if(startDate && endDate) {
            startDate.addEventListener('change', function() {
                if(this.value && endDate.value && this.value > endDate.value) {
                    endDate.value = this.value;
                }
            });
            
            endDate.addEventListener('change', function() {
                if(this.value && startDate.value && this.value < startDate.value) {
                    startDate.value = this.value;
                }
            });
        }
        
        // Auto-refresh on filter change
        const filters = document.querySelectorAll('.filter-section select, .filter-section input');
        filters.forEach(filter => {
            filter.addEventListener('change', function() {
                if(this.closest('form').dataset.autoSubmit === 'true') {
                    this.closest('form').submit();
                }
            });
        });
        
        // Chart initialization
        if(typeof Chart !== 'undefined') {
            initReportCharts();
        }
    }

    function initReportCharts() {
        // Initialize any report charts here
        const chartElements = document.querySelectorAll('canvas');
        if(chartElements.length > 0) {
            // Charts are already initialized in the PHP file
        }
    }

    // Call the function
    initReports();

    // -----------------------------------------------------------------
    // 8. Export Functions (for reports)
    // -----------------------------------------------------------------
    function downloadReport(format) {
        const table = document.getElementById('reportTable');
        let filename = 'HR_Report_' + new Date().toISOString().split('T')[0];
        
        switch(format) {
            case 'excel':
                exportToExcel(table, filename + '.xlsx');
                break;
            case 'pdf':
                exportToPDF(table, filename + '.pdf');
                break;
            case 'csv':
                exportToCSV(table, filename + '.csv');
                break;
        }
    }

    function exportToCSV(table, filename) {
        let csv = [];
        const rows = table.querySelectorAll('tr');
        
        for(let i = 0; i < rows.length; i++) {
            const row = [], cols = rows[i].querySelectorAll('td, th');
            
            for(let j = 0; j < cols.length; j++) {
                row.push('"' + cols[j].innerText.replace(/"/g, '""') + '"');
            }
            
            csv.push(row.join(','));
        }
        
        const csvString = csv.join('\n');
        const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        
        if(navigator.msSaveBlob) {
            navigator.msSaveBlob(blob, filename);
        } else {
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
    // attendance.js - නිවැරදි AJAX call
function checkIn() {
    $.ajax({
        url: 'api/attendance.php',
        type: 'POST',
        data: { action: 'check_in' },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                showNotification('success', response.message);
                updateAttendanceStatus();
            } else {
                showNotification('error', response.message);
            }
        },
        error: function() {
            showNotification('error', 'Network error. Please try again.');
        }
    });
}

function checkOut() {
    $.ajax({
        url: 'api/attendance.php',
        type: 'POST',
        data: { action: 'check_out' },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                showNotification('success', response.message);
                updateAttendanceStatus();
            } else {
                showNotification('error', response.message);
            }
        },
        error: function() {
            showNotification('error', 'Network error. Please try again.');
        }
    });
}

function updateAttendanceStatus() {
    $.ajax({
        url: 'api/attendance.php',
        type: 'POST',
        data: { action: 'get_status' },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                // Update UI elements
                if(response.checked_in) {
                    $('#checkInBtn').prop('disabled', true);
                    $('#checkOutBtn').prop('disabled', false);
                    $('#checkInTime').text(response.check_in_time_formatted);
                }
                if(response.checked_out) {
                    $('#checkOutBtn').prop('disabled', true);
                    $('#checkOutTime').text(response.check_out_time_formatted);
                    $('#totalHours').text(response.total_hours + ' hours');
                }
            }
        }
    });
}

// Auto refresh every 30 seconds
setInterval(updateAttendanceStatus, 30000);

}); // End of DOMContentLoaded