@extends('layouts.dashboard')

@section('title', 'Reports & Analytics')

@section('content')
<div class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-8">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">Reports & Analytics</h1>
            <p class="text-gray-600 mt-1">Generate comprehensive reports for your system data</p>
        </div>
        <div class="mt-4 md:mt-0">
            <button onclick="showQuickStats()" 
                    class="inline-flex items-center px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg transition duration-200">
                <i class="fas fa-chart-bar mr-2"></i> Quick Stats
            </button>
        </div>
    </div>

    <!-- Report Types Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-10">
        <!-- User Report Card -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 hover:shadow-md transition-shadow duration-200">
            <div class="flex items-center mb-5">
                <div class="p-3 rounded-xl bg-blue-50 text-blue-600">
                    <i class="fas fa-users text-xl"></i>
                </div>
                <div class="ml-4">
                    <h3 class="font-semibold text-gray-900">User Reports</h3>
                    <p class="text-sm text-gray-600">Employee and user analytics</p>
                </div>
            </div>
            <ul class="space-y-2 text-sm text-gray-600 mb-5">
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>User activity & status</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Department-wise distribution</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Role-based analytics</span>
                </li>
            </ul>
            <button onclick="selectReportType('users')" 
                    class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition duration-200 shadow-sm hover:shadow-md">
                <i class="fas fa-file-alt mr-2"></i> Generate Report
            </button>
        </div>

        <!-- Visit Report Card -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 hover:shadow-md transition-shadow duration-200">
            <div class="flex items-center mb-5">
                <div class="p-3 rounded-xl bg-emerald-50 text-emerald-600">
                    <i class="fas fa-map-marker-alt text-xl"></i>
                </div>
                <div class="ml-4">
                    <h3 class="font-semibold text-gray-900">Visit Reports</h3>
                    <p class="text-sm text-gray-600">Field visit analytics</p>
                </div>
            </div>
            <ul class="space-y-2 text-sm text-gray-600 mb-5">
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Visit completion rates</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Employee performance</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Geographical analysis</span>
                </li>
            </ul>
            <button onclick="selectReportType('visits')" 
                    class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-lg transition duration-200 shadow-sm hover:shadow-md">
                <i class="fas fa-file-alt mr-2"></i> Generate Report
            </button>
        </div>

        <!-- Leave Report Card -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 hover:shadow-md transition-shadow duration-200">
            <div class="flex items-center mb-5">
                <div class="p-3 rounded-xl bg-amber-50 text-amber-600">
                    <i class="fas fa-calendar-alt text-xl"></i>
                </div>
                <div class="ml-4">
                    <h3 class="font-semibold text-gray-900">Leave Reports</h3>
                    <p class="text-sm text-gray-600">Leave management analytics</p>
                </div>
            </div>
            <ul class="space-y-2 text-sm text-gray-600 mb-5">
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Leave approval rates</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Employee leave patterns</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Department-wise analysis</span>
                </li>
            </ul>
            <button onclick="selectReportType('leaves')" 
                    class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-amber-600 hover:bg-amber-700 text-white font-medium rounded-lg transition duration-200 shadow-sm hover:shadow-md">
                <i class="fas fa-file-alt mr-2"></i> Generate Report
            </button>
        </div>

        <!-- Payroll Report Card -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 hover:shadow-md transition-shadow duration-200">
            <div class="flex items-center mb-5">
                <div class="p-3 rounded-xl bg-purple-50 text-purple-600">
                    <i class="fas fa-money-bill-wave text-xl"></i>
                </div>
                <div class="ml-4">
                    <h3 class="font-semibold text-gray-900">Payroll Reports</h3>
                    <p class="text-sm text-gray-600">Salary and payment analytics</p>
                </div>
            </div>
            <ul class="space-y-2 text-sm text-gray-600 mb-5">
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Monthly payroll summaries</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Salary distribution</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Payment status tracking</span>
                </li>
            </ul>
            <button onclick="selectReportType('payroll')" 
                    class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-purple-600 hover:bg-purple-700 text-white font-medium rounded-lg transition duration-200 shadow-sm hover:shadow-md">
                <i class="fas fa-file-alt mr-2"></i> Generate Report
            </button>
        </div>

        <!-- Client Report Card -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 hover:shadow-md transition-shadow duration-200">
            <div class="flex items-center mb-5">
                <div class="p-3 rounded-xl bg-red-50 text-red-600">
                    <i class="fas fa-handshake text-xl"></i>
                </div>
                <div class="ml-4">
                    <h3 class="font-semibold text-gray-900">Client Reports</h3>
                    <p class="text-sm text-gray-600">Client management analytics</p>
                </div>
            </div>
            <ul class="space-y-2 text-sm text-gray-600 mb-5">
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Client distribution</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Geographical analysis</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Client activity status</span>
                </li>
            </ul>
            <button onclick="selectReportType('clients')" 
                    class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg transition duration-200 shadow-sm hover:shadow-md">
                <i class="fas fa-file-alt mr-2"></i> Generate Report
            </button>
        </div>

        <!-- Performance Report Card -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 hover:shadow-md transition-shadow duration-200">
            <div class="flex items-center mb-5">
                <div class="p-3 rounded-xl bg-indigo-50 text-indigo-600">
                    <i class="fas fa-chart-line text-xl"></i>
                </div>
                <div class="ml-4">
                    <h3 class="font-semibold text-gray-900">Performance Reports</h3>
                    <p class="text-sm text-gray-600">Employee performance analytics</p>
                </div>
            </div>
            <ul class="space-y-2 text-sm text-gray-600 mb-5">
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Visit completion rates</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Employee productivity</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-check-circle text-emerald-500 mr-2 mt-0.5"></i>
                    <span>Department performance</span>
                </li>
            </ul>
            <button onclick="selectReportType('performance')" 
                    class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-medium rounded-lg transition duration-200 shadow-sm hover:shadow-md">
                <i class="fas fa-file-alt mr-2"></i> Generate Report
            </button>
        </div>
    </div>

    <!-- Report Generation Form -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden mb-8">
        <!-- Form Header -->
        <div class="px-6 py-5 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
            <h2 class="text-lg font-semibold text-gray-900">Generate Custom Report</h2>
            <p class="text-sm text-gray-600 mt-1">Configure and generate detailed reports</p>
        </div>
        
        <div class="p-6">
            <form action="{{ route('reports.generate') }}" method="POST" id="reportForm">
                @csrf
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    <!-- Report Configuration -->
                    <div class="space-y-6">
                        <!-- Report Type -->
                        <div>
                            <label for="report_type" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-file-alt mr-2 text-blue-500"></i>Report Type *
                            </label>
                            <select name="report_type" 
                                    id="report_type" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                                    required>
                                <option value="">Select Report Type</option>
                                <option value="users">User Management Report</option>
                                <option value="visits">Visit Management Report</option>
                                <option value="leaves">Leave Management Report</option>
                                <option value="payroll">Payroll Management Report</option>
                                <option value="clients">Client Management Report</option>
                                <option value="performance">Performance Report</option>
                                <option value="summary">System Summary Report</option>
                            </select>
                        </div>

                        <!-- Date Range -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-calendar-alt mr-2 text-blue-500"></i>Date Range
                            </label>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <input type="date" 
                                           name="date_from" 
                                           id="date_from"
                                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                                           value="{{ date('Y-m-01') }}">
                                </div>
                                <div>
                                    <input type="date" 
                                           name="date_to" 
                                           id="date_to"
                                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                                           value="{{ date('Y-m-t') }}">
                                </div>
                            </div>
                        </div>

                        <!-- Filters (Dynamic based on report type) -->
                        <div id="departmentFilter" class="hidden">
                            <label for="department_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-building mr-2 text-blue-500"></i>Department
                            </label>
                            <select name="department_id" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200">
                                <option value="">All Departments</option>
                                @foreach(\App\Models\Department::all() as $department)
                                <option value="{{ $department->id }}">{{ $department->name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div id="employeeFilter" class="hidden">
                            <label for="employee_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-user-tie mr-2 text-blue-500"></i>Employee
                            </label>
                            <select name="employee_id" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200">
                                <option value="">All Employees</option>
                                @foreach(\App\Models\User::role('employee')->get() as $employee)
                                <option value="{{ $employee->id }}">{{ $employee->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <!-- Export Configuration -->
                    <div class="space-y-6">
                        <!-- Status Filter -->
                        <div id="statusFilter" class="hidden">
                            <label for="status" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-info-circle mr-2 text-blue-500"></i>Status
                            </label>
                            <select name="status" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200">
                                <option value="">All Status</option>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>

                        <!-- Governorate Filter -->
                        <div id="governorateFilter" class="hidden">
                            <label for="governorate_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-map mr-2 text-blue-500"></i>Governorate
                            </label>
                            <select name="governorate_id" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200">
                                <option value="">All Governorates</option>
                                @foreach(\App\Models\Governorate::all() as $governorate)
                                <option value="{{ $governorate->id }}">{{ $governorate->name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Export Format -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-3">
                                <i class="fas fa-download mr-2 text-blue-500"></i>Export Format
                            </label>
                            <div class="grid grid-cols-3 gap-3">
                                <label class="flex flex-col items-center p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition duration-200">
                                    <input type="radio" 
                                           name="format" 
                                           value="html" 
                                           checked 
                                           class="mb-2">
                                    <i class="fas fa-globe text-blue-500 text-xl mb-2"></i>
                                    <span class="text-sm font-medium">Web View</span>
                                </label>
                                
                                <label class="flex flex-col items-center p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition duration-200">
                                    <input type="radio" 
                                           name="format" 
                                           value="excel" 
                                           class="mb-2">
                                    <i class="fas fa-file-excel text-emerald-500 text-xl mb-2"></i>
                                    <span class="text-sm font-medium">Excel</span>
                                </label>
                                
                                <label class="flex flex-col items-center p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition duration-200">
                                    <input type="radio" 
                                           name="format" 
                                           value="pdf" 
                                           class="mb-2">
                                    <i class="fas fa-file-pdf text-red-500 text-xl mb-2"></i>
                                    <span class="text-sm font-medium">PDF</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Form Actions -->
                <div class="mt-10 pt-8 border-t border-gray-200 flex justify-end space-x-3">
                    <button type="reset" 
                            class="px-5 py-3 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition duration-200">
                        <i class="fas fa-redo mr-2"></i> Reset
                    </button>
                    <button type="submit" 
                            class="px-5 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition duration-200 shadow-sm hover:shadow-md">
                        <i class="fas fa-play-circle mr-2"></i> Generate Report
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Recent Reports -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <!-- Section Header -->
        <div class="px-6 py-5 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100">
            <h2 class="text-lg font-semibold text-gray-900">Recent Reports</h2>
            <p class="text-sm text-gray-600 mt-1">View your recently generated reports</p>
        </div>
        
        <div class="p-6">
            @php
                // Check if recentReports variable exists, otherwise use empty array
                $recentReports = $recentReports ?? [];
            @endphp
            
            @if(count($recentReports) > 0)
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Report Type</th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Date Range</th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Generated On</th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        @foreach($recentReports as $report)
                        <tr class="hover:bg-gray-50 transition-colors duration-150">
                            <td class="px-6 py-4">
                                <div class="flex items-center">
                                    @php
                                        $reportIcons = [
                                            'users' => 'fa-users text-blue-500',
                                            'visits' => 'fa-map-marker-alt text-emerald-500',
                                            'leaves' => 'fa-calendar-alt text-amber-500',
                                            'payroll' => 'fa-money-bill-wave text-purple-500',
                                            'clients' => 'fa-handshake text-red-500',
                                            'performance' => 'fa-chart-line text-indigo-500',
                                            'summary' => 'fa-chart-bar text-gray-500'
                                        ];
                                    @endphp
                                    <i class="fas {{ $reportIcons[$report->type] ?? 'fa-file-alt text-gray-500' }} mr-3 text-lg"></i>
                                    <div>
                                        <div class="text-sm font-medium text-gray-900">{{ $report->name ?? 'Unnamed Report' }}</div>
                                        <div class="text-xs text-gray-500">{{ isset($report->format) ? strtoupper($report->format) : 'HTML' }} format</div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-900">
                                {{ isset($report->date_from) ? \Carbon\Carbon::parse($report->date_from)->format('M d') : 'N/A' }} - 
                                {{ isset($report->date_to) ? \Carbon\Carbon::parse($report->date_to)->format('M d, Y') : 'N/A' }}
                            </td>
                            <td class="px-6 py-4">
                                <div class="text-sm text-gray-900">{{ isset($report->created_at) ? \Carbon\Carbon::parse($report->created_at)->format('M d, Y') : 'N/A' }}</div>
                                <div class="text-xs text-gray-500">{{ isset($report->created_at) ? \Carbon\Carbon::parse($report->created_at)->format('h:i A') : '' }}</div>
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex items-center space-x-2">
                                    @if(isset($report->id))
                                    <a href="{{ route('reports.view', $report->id) }}" 
                                       class="text-blue-600 hover:text-blue-800 hover:bg-blue-50 p-2 rounded-lg transition-colors duration-200"
                                       title="View Report">
                                        <i class="fas fa-eye text-sm"></i>
                                    </a>
                                    <a href="{{ route('reports.download', $report->id) }}" 
                                       class="text-emerald-600 hover:text-emerald-800 hover:bg-emerald-50 p-2 rounded-lg transition-colors duration-200"
                                       title="Download Report">
                                        <i class="fas fa-download text-sm"></i>
                                    </a>
                                    @else
                                    <span class="text-gray-400 text-sm">Actions not available</span>
                                    @endif
                                </div>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
            @else
            <div class="text-center py-12">
                <div class="w-20 h-20 mx-auto mb-4 text-gray-300">
                    <i class="fas fa-file-alt text-5xl"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-700 mb-2">No Recent Reports</h3>
                <p class="text-gray-500 mb-6 max-w-md mx-auto">You haven't generated any reports yet. Use the form above to create your first report.</p>
            </div>
            @endif
        </div>
    </div>
</div>

<!-- Quick Stats Modal -->
<div id="quickStatsModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50 transition-opacity duration-300">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-2/3 xl:w-1/2 shadow-xl rounded-xl bg-white transform transition-transform duration-300">
        <div class="flex justify-between items-center mb-6">
            <div>
                <h3 class="text-lg font-semibold text-gray-900">System Quick Stats</h3>
                <p class="text-sm text-gray-600 mt-1">Real-time system statistics and insights</p>
            </div>
            <button onclick="closeQuickStats()" 
                    class="text-gray-400 hover:text-gray-600 hover:bg-gray-100 p-2 rounded-lg transition duration-200">
                <i class="fas fa-times text-lg"></i>
            </button>
        </div>
        
        <div id="quickStatsContent" class="space-y-6">
            <div class="text-center">
                <div class="inline-block animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-blue-500"></div>
                <p class="mt-3 text-gray-600">Loading statistics...</p>
            </div>
        </div>
        
        <div class="mt-8 pt-6 border-t border-gray-200 flex justify-end">
            <button onclick="closeQuickStats()" 
                    class="px-4 py-2.5 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition duration-200">
                Close
            </button>
        </div>
    </div>
</div>

<script>
// Report type selection
function selectReportType(type) {
    const reportType = document.getElementById('report_type');
    reportType.value = type;
    updateFilters(type);
    reportType.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

// Update filters based on report type
function updateFilters(reportType) {
    // Hide all filters first
    const filters = ['departmentFilter', 'employeeFilter', 'statusFilter', 'governorateFilter'];
    filters.forEach(filter => {
        document.getElementById(filter).classList.add('hidden');
    });

    // Show relevant filters based on report type
    switch(reportType) {
        case 'users':
            document.getElementById('departmentFilter').classList.remove('hidden');
            document.getElementById('statusFilter').classList.remove('hidden');
            break;
        case 'visits':
        case 'leaves':
        case 'performance':
            document.getElementById('employeeFilter').classList.remove('hidden');
            document.getElementById('departmentFilter').classList.remove('hidden');
            break;
        case 'payroll':
            document.getElementById('employeeFilter').classList.remove('hidden');
            document.getElementById('statusFilter').classList.remove('hidden');
            break;
        case 'clients':
            document.getElementById('governorateFilter').classList.remove('hidden');
            document.getElementById('statusFilter').classList.remove('hidden');
            break;
    }
}

// Quick stats modal
function showQuickStats() {
    const modal = document.getElementById('quickStatsModal');
    const content = document.getElementById('quickStatsContent');
    
    modal.classList.remove('hidden');
    setTimeout(() => {
        modal.style.opacity = '1';
    }, 10);
    
    // Show loading state
    content.innerHTML = `
        <div class="text-center py-8">
            <div class="inline-block animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-blue-500"></div>
            <p class="mt-3 text-gray-600">Loading system statistics...</p>
        </div>
    `;
    
    try {
        // Fetch quick stats via AJAX
        fetch('{{ route("reports.dashboard-stats") }}', {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Handle the case where data might be null or undefined
            const safeData = data || {};
            
            content.innerHTML = `
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-5 text-center border border-blue-200">
                        <div class="text-3xl font-bold text-blue-600">${safeData.total_employees || 0}</div>
                        <div class="text-sm font-medium text-blue-800 mt-2">Total Employees</div>
                        <div class="text-xs text-blue-600 mt-1">
                            <i class="fas fa-users mr-1"></i> ${safeData.active_employees || 0} active
                        </div>
                    </div>
                    
                    <div class="bg-gradient-to-br from-emerald-50 to-emerald-100 rounded-xl p-5 text-center border border-emerald-200">
                        <div class="text-3xl font-bold text-emerald-600">${safeData.active_visits_today || 0}</div>
                        <div class="text-sm font-medium text-emerald-800 mt-2">Active Visits Today</div>
                        <div class="text-xs text-emerald-600 mt-1">
                            <i class="fas fa-check-circle mr-1"></i> ${safeData.completed_visits_today || 0} completed
                        </div>
                    </div>
                    
                    <div class="bg-gradient-to-br from-amber-50 to-amber-100 rounded-xl p-5 text-center border border-amber-200">
                        <div class="text-3xl font-bold text-amber-600">${safeData.pending_leaves || 0}</div>
                        <div class="text-sm font-medium text-amber-800 mt-2">Pending Leaves</div>
                        <div class="text-xs text-amber-600 mt-1">
                            <i class="fas fa-calendar-check mr-1"></i> ${safeData.approved_leaves || 0} approved this month
                        </div>
                    </div>
                    
                    <div class="bg-gradient-to-br from-red-50 to-red-100 rounded-xl p-5 text-center border border-red-200">
                        <div class="text-3xl font-bold text-red-600">${safeData.total_clients || 0}</div>
                        <div class="text-sm font-medium text-red-800 mt-2">Total Clients</div>
                        <div class="text-xs text-red-600 mt-1">
                            <i class="fas fa-handshake mr-1"></i> ${safeData.active_clients || 0} active
                        </div>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <!-- Recent Payrolls -->
                    <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-5 border border-purple-200">
                        <h4 class="font-semibold text-purple-800 mb-4 flex items-center">
                            <i class="fas fa-money-check-alt mr-2"></i> Recent Payrolls
                        </h4>
                        <div class="space-y-3">
                            ${safeData.recent_payrolls && safeData.recent_payrolls.length > 0 ? 
                                safeData.recent_payrolls.map(payroll => `
                                    <div class="flex justify-between items-center p-3 bg-white rounded-lg border border-purple-100">
                                        <div>
                                            <div class="font-medium text-gray-900">${payroll.employee?.name || 'Unknown'}</div>
                                            <div class="text-xs text-gray-500">${payroll.pay_period_start || ''} - ${payroll.pay_period_end || ''}</div>
                                        </div>
                                        <div class="text-right">
                                            <div class="font-bold text-purple-600">${payroll.net_salary || 0} EGP</div>
                                            <div class="text-xs text-gray-500">${payroll.status || 'unknown'}</div>
                                        </div>
                                    </div>
                                `).join('') :
                                '<p class="text-gray-500 text-center py-4">No recent payrolls</p>'
                            }
                        </div>
                    </div>
                    
                    <!-- Monthly Visit Trend -->
                    <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-5 border border-blue-200">
                        <h4 class="font-semibold text-blue-800 mb-4 flex items-center">
                            <i class="fas fa-chart-line mr-2"></i> Monthly Visit Trend
                        </h4>
                        <div class="h-48 flex items-end space-x-2 pt-4">
                            ${safeData.monthly_visit_trend && safeData.monthly_visit_trend.length > 0 ?
                                safeData.monthly_visit_trend.map(item => {
                                    const maxVisits = Math.max(...safeData.monthly_visit_trend.map(i => i.visits || 0));
                                    const heightPercent = maxVisits > 0 ? ((item.visits || 0) / maxVisits) * 100 : 0;
                                    return `
                                        <div class="flex-1 flex flex-col items-center">
                                            <div class="w-full bg-gradient-to-t from-blue-400 to-blue-500 rounded-t-lg" 
                                                 style="height: ${heightPercent}%"></div>
                                            <div class="text-xs text-gray-600 mt-2">${item.month || ''}</div>
                                            <div class="text-xs font-semibold text-gray-900 mt-1">${item.visits || 0}</div>
                                        </div>
                                    `;
                                }).join('') :
                                '<p class="text-gray-500 text-center py-8 w-full">No visit data available</p>'
                            }
                        </div>
                    </div>
                </div>
                
                <div class="bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl p-5 border border-gray-200">
                    <h4 class="font-semibold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-info-circle mr-2"></i> System Information
                    </h4>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div class="text-center p-3 bg-white rounded-lg border border-gray-200">
                            <div class="text-sm text-gray-500">Database Size</div>
                            <div class="text-lg font-semibold text-gray-900 mt-1">${safeData.database_size || 'N/A'}</div>
                        </div>
                        <div class="text-center p-3 bg-white rounded-lg border border-gray-200">
                            <div class="text-sm text-gray-500">Uptime</div>
                            <div class="text-lg font-semibold text-gray-900 mt-1">${safeData.uptime || 'N/A'}</div>
                        </div>
                        <div class="text-center p-3 bg-white rounded-lg border border-gray-200">
                            <div class="text-sm text-gray-500">Users Online</div>
                            <div class="text-lg font-semibold text-gray-900 mt-1">${safeData.users_online || 0}</div>
                        </div>
                        <div class="text-center p-3 bg-white rounded-lg border border-gray-200">
                            <div class="text-sm text-gray-500">Report Count</div>
                            <div class="text-lg font-semibold text-gray-900 mt-1">${safeData.total_reports || 0}</div>
                        </div>
                    </div>
                </div>
            `;
        })
        .catch(error => {
            console.error('Error loading quick stats:', error);
            content.innerHTML = `
                <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-triangle text-red-500 text-xl mr-3"></i>
                        <div>
                            <p class="font-medium text-red-800">Failed to load statistics</p>
                            <p class="text-red-700 text-sm mt-1">Please try again later or contact support</p>
                        </div>
                    </div>
                </div>
            `;
        });
    } catch (error) {
        console.error('Error in showQuickStats:', error);
        content.innerHTML = `
            <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                <div class="flex items-center">
                    <i class="fas fa-exclamation-triangle text-red-500 text-xl mr-3"></i>
                    <div>
                        <p class="font-medium text-red-800">Error loading statistics</p>
                        <p class="text-red-700 text-sm mt-1">An unexpected error occurred</p>
                    </div>
                </div>
            </div>
        `;
    }
}

function closeQuickStats() {
    const modal = document.getElementById('quickStatsModal');
    modal.style.opacity = '0';
    setTimeout(() => {
        modal.classList.add('hidden');
    }, 300);
}

// Initialize event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Update filters when report type changes
    const reportTypeSelect = document.getElementById('report_type');
    if (reportTypeSelect) {
        reportTypeSelect.addEventListener('change', function() {
            updateFilters(this.value);
        });
    }
    
    // Form validation
    const reportForm = document.getElementById('reportForm');
    if (reportForm) {
        reportForm.addEventListener('submit', function(e) {
            const dateFrom = document.getElementById('date_from');
            const dateTo = document.getElementById('date_to');
            
            if (dateFrom && dateTo) {
                const dateFromVal = new Date(dateFrom.value);
                const dateToVal = new Date(dateTo.value);
                
                if (dateToVal < dateFromVal) {
                    e.preventDefault();
                    alert('To date must be after or equal to From date');
                    return false;
                }
            }
            
            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            if (submitBtn) {
                const originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Generating...';
                submitBtn.disabled = true;
                
                setTimeout(() => {
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }, 5000);
            }
            
            return true;
        });
    }
    
    // Set default dates
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    
    const dateFromInput = document.getElementById('date_from');
    const dateToInput = document.getElementById('date_to');
    
    if (dateFromInput) {
        dateFromInput.valueAsDate = firstDay;
    }
    if (dateToInput) {
        dateToInput.valueAsDate = lastDay;
    }
    
    // Close modal when clicking outside
    const quickStatsModal = document.getElementById('quickStatsModal');
    if (quickStatsModal) {
        quickStatsModal.addEventListener('click', function(e) {
            if (e.target.id === 'quickStatsModal') {
                closeQuickStats();
            }
        });
    }
});
</script>

<style>
/* Custom animations */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

#quickStatsModal > div {
    animation: fadeIn 0.3s ease-out;
}

/* Smooth transitions */
* {
    transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform;
    transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
    transition-duration: 200ms;
}

/* Custom scrollbar */
.max-h-64::-webkit-scrollbar {
    width: 6px;
}

.max-h-64::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.max-h-64::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.max-h-64::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
}

/* Form radio button styling */
input[type="radio"] {
    accent-color: #3b82f6;
}
</style>
@endsection