<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leave Reports</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#146CAA',
                        primaryLight: '#E1F0FA',
                        secondary: '#6b7280',
                        success: '#107C10',
                        warning: '#F68C1E',
                        danger: '#D83B01',
                        info: '#0078D4',
                        gray50: '#FAF9F8',
                        gray100: '#F3F2F1',
                        gray200: '#EDEBE9',
                        gray300: '#E1DFDD',
                        gray400: '#C8C6C4',
                        gray500: '#A19F9D',
                        gray600: '#605E5C',
                        gray700: '#323130',
                        gray800: '#201F1E',
                        gray900: '#000000'
                    }
                }
            }
        }
    </script>
    <style>
        .report-card {
            transition: all 0.3s ease;
            border: 1px solid #EDEBE9;
            border-radius: 8px;
            background: white;
        }
        
        .report-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
            border-color: #146CAA;
        }
        
        .report-icon {
            width: 64px;
            height: 64px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
        }
        
        .icon-blue {
            background-color: #E1F0FA;
        }
        
        .icon-green {
            background-color: #E1F0FA;
        }
        
        .icon-purple {
            background-color: #F3E8FF;
        }
        
        .icon-orange {
            background-color: #FEF7E0;
        }
        
        .icon-red {
            background-color: #FEE8E6;
        }
        
        .icon-teal {
            background-color: #E1F0FA;
        }
    </style>
</head>
<body class="bg-gray50">
    @include('accounting.partials.sidebar')

    <div class="lg:ml-64">
        <!-- Header -->
        <header class="bg-white border-b border-gray200 py-4 px-6">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-xl font-bold text-gray900">Leave Reports</h1>
                    <nav class="flex space-x-2 text-sm text-gray600 mt-1">
                        <a href="{{ route('admin.accounting.index') }}" class="hover:text-primary">Dashboard</a>
                        <span>/</span>
                        <a href="{{ route('admin.accounting.payroll.index') }}" class="hover:text-primary">Payroll</a>
                        <span>/</span>
                        <a href="{{ route('admin.accounting.payroll.leave.index') }}" class="hover:text-primary">Leave Management</a>
                        <span>/</span>
                        <span class="text-gray900">Reports</span>
                    </nav>
                </div>
            </div>
        </header>

        <main class="p-6">
            <!-- Success/Error Messages -->
            @if(session('success'))
                <div class="mb-6 bg-green-50 border border-green-200 rounded-lg p-4 animate-fade-in">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <i class="fas fa-check-circle text-green-500 mr-2"></i>
                            <span class="text-green-800 font-medium">{{ session('success') }}</span>
                        </div>
                        <button onclick="this.parentElement.parentElement.remove()" class="text-green-600 hover:text-green-800">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            @endif

            <!-- Reports Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- Leave Utilization Report -->
                <a href="{{ route('admin.accounting.payroll.leave.reports.leave-utilization') }}" 
                   class="report-card p-6 hover:no-underline">
                    <div class="text-center">
                        <div class="report-icon icon-blue mx-auto">
                            <i class="fas fa-chart-pie text-primary text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-gray900 mb-2">Leave Utilization Report</h3>
                        <p class="text-gray600 text-sm mb-4">
                            Analyze leave usage patterns by department, employee, and leave type
                        </p>
                        <div class="text-primary text-sm font-medium">
                            View Report <i class="fas fa-arrow-right ml-1"></i>
                        </div>
                    </div>
                </a>

                <!-- Leave Calendar -->
                <a href="{{ route('admin.accounting.payroll.leave.reports.leave-calendar') }}" 
                   class="report-card p-6 hover:no-underline">
                    <div class="text-center">
                        <div class="report-icon icon-green mx-auto">
                            <i class="fas fa-calendar-alt text-success text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-gray900 mb-2">Leave Calendar</h3>
                        <p class="text-gray600 text-sm mb-4">
                            Visual calendar view of all approved leaves and upcoming time off
                        </p>
                        <div class="text-primary text-sm font-medium">
                            View Calendar <i class="fas fa-arrow-right ml-1"></i>
                        </div>
                    </div>
                </a>

                <!-- Balance Summary -->
                <div class="report-card p-6">
                    <div class="text-center">
                        <div class="report-icon icon-purple mx-auto">
                            <i class="fas fa-balance-scale text-purple-600 text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-gray900 mb-2">Balance Summary</h3>
                        <p class="text-gray600 text-sm mb-4">
                            Comprehensive overview of all employee leave balances
                        </p>
                        <button onclick="generateBalanceSummary()" 
                                class="w-full bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90 flex items-center justify-center gap-2">
                            <i class="fas fa-download"></i>
                            Generate Report
                        </button>
                    </div>
                </div>

                <!-- Accrual Report -->
                <div class="report-card p-6">
                    <div class="text-center">
                        <div class="report-icon icon-orange mx-auto">
                            <i class="fas fa-calculator text-warning text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-gray900 mb-2">Accrual Report</h3>
                        <p class="text-gray600 text-sm mb-4">
                            Track leave accruals and adjustments over time
                        </p>
                        <button onclick="generateAccrualReport()" 
                                class="w-full bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90 flex items-center justify-center gap-2">
                            <i class="fas fa-download"></i>
                            Generate Report
                        </button>
                    </div>
                </div>

                <!-- Absence Report -->
                <div class="report-card p-6">
                    <div class="text-center">
                        <div class="report-icon icon-red mx-auto">
                            <i class="fas fa-user-times text-danger text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-gray900 mb-2">Absence Report</h3>
                        <p class="text-gray600 text-sm mb-4">
                            Detailed analysis of employee absences and patterns
                        </p>
                        <button onclick="generateAbsenceReport()" 
                                class="w-full bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90 flex items-center justify-center gap-2">
                            <i class="fas fa-download"></i>
                            Generate Report
                        </button>
                    </div>
                </div>

                <!-- Compliance Report -->
                <div class="report-card p-6">
                    <div class="text-center">
                        <div class="report-icon icon-teal mx-auto">
                            <i class="fas fa-clipboard-check text-info text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-gray900 mb-2">Compliance Report</h3>
                        <p class="text-gray600 text-sm mb-4">
                            Ensure compliance with leave policies and regulations
                        </p>
                        <button onclick="generateComplianceReport()" 
                                class="w-full bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90 flex items-center justify-center gap-2">
                            <i class="fas fa-download"></i>
                            Generate Report
                        </button>
                    </div>
                </div>
            </div>

            <!-- Quick Stats -->
            <div class="mt-8">
                <div class="bg-white rounded-lg border border-gray200 p-6">
                    <h2 class="text-lg font-semibold text-gray900 mb-4">Quick Statistics</h2>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                        <div class="text-center p-4 bg-gray50 rounded-lg">
                            <div class="text-2xl font-bold text-primary mb-1" id="totalRequests">0</div>
                            <div class="text-sm text-gray600">Total Leave Requests</div>
                        </div>
                        <div class="text-center p-4 bg-gray50 rounded-lg">
                            <div class="text-2xl font-bold text-success mb-1" id="approvalRate">0%</div>
                            <div class="text-sm text-gray600">Approval Rate</div>
                        </div>
                        <div class="text-center p-4 bg-gray50 rounded-lg">
                            <div class="text-2xl font-bold text-warning mb-1" id="avgLeaveDays">0</div>
                            <div class="text-sm text-gray600">Avg. Leave Days/Employee</div>
                        </div>
                        <div class="text-center p-4 bg-gray50 rounded-lg">
                            <div class="text-2xl font-bold text-info mb-1" id="utilizationRate">0%</div>
                            <div class="text-sm text-gray600">Leave Utilization Rate</div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Base URL configuration
        const BASE_URL = '{{ url('/') }}';

        // Load quick stats
        async function loadQuickStats() {
            try {
                const response = await fetch(`${BASE_URL}/admin/accounting/payroll/leave/stats`);
                const data = await response.json();
                
                if (data.success) {
                    const stats = data.stats;
                    
                    // Update stats display
                    document.getElementById('totalRequests').textContent = stats.total_requests || 0;
                    
                    // Calculate approval rate
                    const approvalRate = stats.total_requests > 0 ? 
                        ((stats.approved_this_month || 0) / stats.total_requests * 100).toFixed(1) : 0;
                    document.getElementById('approvalRate').textContent = `${approvalRate}%`;
                    
                    // Calculate average leave days (simplified)
                    const avgLeaveDays = stats.taken_this_month > 0 ? 
                        (stats.taken_this_month / (stats.approved_this_month || 1)).toFixed(1) : 0;
                    document.getElementById('avgLeaveDays').textContent = avgLeaveDays;
                    
                    // Calculate utilization rate (simplified)
                    const utilizationRate = stats.total_requests > 0 ? 
                        ((stats.taken_this_month || 0) / stats.total_requests * 100).toFixed(1) : 0;
                    document.getElementById('utilizationRate').textContent = `${utilizationRate}%`;
                }
            } catch (error) {
                console.error('Error loading quick stats:', error);
            }
        }

        // Report generation functions
        function generateBalanceSummary() {
            // Show loading state
            const button = event.target;
            const originalText = button.innerHTML;
            button.disabled = true;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Generating...';
            
            // Simulate API call
            setTimeout(() => {
                // Create download link
                const link = document.createElement('a');
                link.href = `${BASE_URL}/admin/accounting/payroll/leave/reports/balance-summary`;
                link.download = `leave-balance-summary-${new Date().toISOString().split('T')[0]}.pdf`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                // Reset button
                button.disabled = false;
                button.innerHTML = originalText;
                
                // Show success message
                showNotification('Balance summary report generated successfully!', 'success');
            }, 1500);
        }

        function generateAccrualReport() {
            const button = event.target;
            const originalText = button.innerHTML;
            button.disabled = true;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Generating...';
            
            setTimeout(() => {
                const link = document.createElement('a');
                link.href = `${BASE_URL}/admin/accounting/payroll/leave/reports/accrual`;
                link.download = `leave-accrual-report-${new Date().toISOString().split('T')[0]}.pdf`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                button.disabled = false;
                button.innerHTML = originalText;
                showNotification('Accrual report generated successfully!', 'success');
            }, 1500);
        }

        function generateAbsenceReport() {
            const button = event.target;
            const originalText = button.innerHTML;
            button.disabled = true;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Generating...';
            
            setTimeout(() => {
                const link = document.createElement('a');
                link.href = `${BASE_URL}/admin/accounting/payroll/leave/reports/absence`;
                link.download = `absence-report-${new Date().toISOString().split('T')[0]}.pdf`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                button.disabled = false;
                button.innerHTML = originalText;
                showNotification('Absence report generated successfully!', 'success');
            }, 1500);
        }

        function generateComplianceReport() {
            const button = event.target;
            const originalText = button.innerHTML;
            button.disabled = true;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Generating...';
            
            setTimeout(() => {
                const link = document.createElement('a');
                link.href = `${BASE_URL}/admin/accounting/payroll/leave/reports/compliance`;
                link.download = `compliance-report-${new Date().toISOString().split('T')[0]}.pdf`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                button.disabled = false;
                button.innerHTML = originalText;
                showNotification('Compliance report generated successfully!', 'success');
            }, 1500);
        }

        // Notification function
        function showNotification(message, type = 'info') {
            const existing = document.querySelector('.quickbooks-notification');
            if (existing) existing.remove();

            const colors = {
                success: 'bg-success',
                error: 'bg-danger',
                info: 'bg-primary',
                warning: 'bg-warning'
            };

            const icons = {
                success: 'fa-check-circle',
                error: 'fa-exclamation-circle',
                info: 'fa-info-circle',
                warning: 'fa-exclamation-triangle'
            };

            const notification = document.createElement('div');
            notification.className = `quickbooks-notification fixed top-4 right-4 ${colors[type]} text-white px-4 py-3 rounded shadow-lg z-50 flex items-center animate-fade-in`;
            notification.innerHTML = `
                <i class="fas ${icons[type]} mr-2"></i>
                <span>${message}</span>
            `;

            document.body.appendChild(notification);

            setTimeout(() => {
                notification.classList.add('animate-fade-out');
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 3000);
        }

        // Add animation styles
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(-10px); }
                to { opacity: 1; transform: translateY(0); }
            }
            @keyframes fadeOut {
                from { opacity: 1; transform: translateY(0); }
                to { opacity: 0; transform: translateY(-10px); }
            }
            .animate-fade-in {
                animation: fadeIn 0.3s ease-out;
            }
            .animate-fade-out {
                animation: fadeOut 0.3s ease-in;
            }
            .quickbooks-notification {
                animation: fadeIn 0.3s ease-out;
            }
        `;
        document.head.appendChild(style);

        // Auto-hide alerts after 5 seconds
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                const alerts = document.querySelectorAll('.bg-green-50, .bg-red-50');
                alerts.forEach(alert => {
                    if (alert) {
                        alert.style.opacity = '0';
                        alert.style.transition = 'opacity 0.5s ease';
                        setTimeout(() => {
                            if (alert.parentNode) {
                                alert.parentNode.removeChild(alert);
                            }
                        }, 500);
                    }
                });
            }, 5000);
            
            // Load quick stats
            loadQuickStats();
            
            // Add hover effects to report cards
            const reportCards = document.querySelectorAll('.report-card');
            reportCards.forEach(card => {
                card.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateY(-4px)';
                    this.style.boxShadow = '0 8px 24px rgba(0, 0, 0, 0.1)';
                    this.style.borderColor = '#146CAA';
                });
                card.addEventListener('mouseleave', function() {
                    this.style.transform = 'translateY(0)';
                    this.style.boxShadow = 'none';
                    this.style.borderColor = '#EDEBE9';
                });
            });
        });
    </script>
</body>
</html>