@extends('layouts.dashboard')

@section('title', 'All Employees Tracking')

@section('content')
<div class="container mx-auto px-4">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">All Employees Tracking</h1>
        <div class="flex space-x-3">
            <a href="{{ route('live-tracking.index') }}" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded flex items-center">
                <i class="fas fa-arrow-left mr-2"></i> Back to Dashboard
            </a>
            <a href="{{ route('live-tracking.map') }}" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded flex items-center">
                <i class="fas fa-map mr-2"></i> View Map
            </a>
        </div>
    </div>

    <!-- Search and Filter -->
    <div class="bg-white shadow-md rounded-lg p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
                <input type="text" id="searchInput" placeholder="Search employees..." 
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div>
                <select id="departmentFilter" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">All Departments</option>
                    @foreach(\App\Models\Department::all() as $department)
                        <option value="{{ $department->id }}">{{ $department->name }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <select id="statusFilter" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">All Status</option>
                    <option value="active">Currently Active</option>
                    <option value="inactive">Not Active</option>
                </select>
            </div>
            <div>
                <button onclick="refreshData()" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded flex items-center justify-center">
                    <i class="fas fa-sync-alt mr-2"></i> Refresh
                </button>
            </div>
        </div>
    </div>

    <!-- Stats -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
        <div class="bg-white shadow rounded-lg p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-600 mr-4">
                    <i class="fas fa-users text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-600">Total Employees</p>
                    <h3 class="text-2xl font-bold">{{ $employees->count() }}</h3>
                </div>
            </div>
        </div>
        
        <div class="bg-white shadow rounded-lg p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-green-100 text-green-600 mr-4">
                    <i class="fas fa-user-check text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-600">Active Now</p>
                    <h3 class="text-2xl font-bold" id="active-now-count">0</h3>
                </div>
            </div>
        </div>
        
        <div class="bg-white shadow rounded-lg p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-purple-100 text-purple-600 mr-4">
                    <i class="fas fa-map-marker-alt text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-600">With Location</p>
                    <h3 class="text-2xl font-bold" id="with-location-count">0</h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Employees Table -->
    <div class="bg-white shadow-md rounded-lg overflow-hidden">
        <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-medium text-gray-500 uppercase tracking-wider">Employee</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Department</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Current Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Last Location</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Last Update</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200" id="employees-table-body">
                    @foreach($employees as $employee)
                    @php
                        $currentVisit = $employee->currentVisit;
                        $isActive = $currentVisit && $currentVisit->status == 'in_progress';
                    @endphp
                    <tr class="employee-row" 
                        data-name="{{ strtolower($employee->name) }}"
                        data-department="{{ $employee->department_id }}"
                        data-status="{{ $isActive ? 'active' : 'inactive' }}">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 h-10 w-10">
                                    <div class="h-10 w-10 rounded-full {{ $isActive ? 'bg-green-600' : 'bg-gray-600' }} flex items-center justify-center text-white">
                                        @if($employee->profile_picture)
                                            <img src="{{ Storage::url($employee->profile_picture) }}" 
                                                 alt="{{ $employee->name }}" 
                                                 class="h-10 w-10 rounded-full">
                                        @else
                                            <i class="fas fa-user"></i>
                                        @endif
                                    </div>
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-medium text-gray-900">{{ $employee->name }}</div>
                                    <div class="text-sm text-gray-500">{{ $employee->employee_id }}</div>
                                    <div class="text-xs text-gray-400">{{ $employee->phone }}</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">
                                @if($employee->department)
                                    <div class="flex items-center">
                                        <i class="fas fa-building mr-2 text-gray-400"></i>
                                        {{ $employee->department->name }}
                                    </div>
                                @else
                                    <span class="text-gray-400">N/A</span>
                                @endif
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            @if($isActive)
                                <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                                    <i class="fas fa-circle animate-pulse mr-1"></i> Active
                                </span>
                                <div class="text-xs text-gray-500 mt-1">
                                    <i class="fas fa-map-marker-alt mr-1"></i> 
                                    {{ $currentVisit->client->name ?? 'On Visit' }}
                                </div>
                            @else
                                <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">
                                    <i class="fas fa-circle mr-1"></i> Not Active
                                </span>
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">
                                @if($currentVisit && $currentVisit->current_address)
                                    <i class="fas fa-map-marker-alt text-red-500 mr-1"></i>
                                    {{ Str::limit($currentVisit->current_address, 30) }}
                                @else
                                    <span class="text-gray-400">Not available</span>
                                @endif
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            @if($currentVisit)
                                {{ $currentVisit->updated_at->diffForHumans() }}
                            @else
                                N/A
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <div class="flex space-x-2">
                                @if($isActive)
                                <a href="{{ route('gps.track', $currentVisit) }}" 
                                   class="text-blue-600 hover:text-blue-900"
                                   title="Track Live">
                                    <i class="fas fa-satellite"></i>
                                </a>
                                <button onclick="getLocation({{ $employee->id }})" 
                                        class="text-green-600 hover:text-green-900"
                                        title="Get Location">
                                    <i class="fas fa-map-marker-alt"></i>
                                </button>
                                @endif
                                <a href="{{ route('live-tracking.history', $employee) }}" 
                                   class="text-purple-600 hover:text-purple-900"
                                   title="View History">
                                    <i class="fas fa-history"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchInput');
    const departmentFilter = document.getElementById('departmentFilter');
    const statusFilter = document.getElementById('statusFilter');
    const employeeRows = document.querySelectorAll('.employee-row');
    
    function filterEmployees() {
        const searchTerm = searchInput.value.toLowerCase();
        const selectedDepartment = departmentFilter.value;
        const selectedStatus = statusFilter.value;
        
        employeeRows.forEach(row => {
            const name = row.getAttribute('data-name');
            const department = row.getAttribute('data-department');
            const status = row.getAttribute('data-status');
            
            let matchesSearch = name.includes(searchTerm);
            let matchesDepartment = !selectedDepartment || department === selectedDepartment;
            let matchesStatus = !selectedStatus || status === selectedStatus;
            
            if (matchesSearch && matchesDepartment && matchesStatus) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
        
        updateStats();
    }
    
    function updateStats() {
        const visibleRows = Array.from(employeeRows).filter(row => row.style.display !== 'none');
        const activeRows = visibleRows.filter(row => row.getAttribute('data-status') === 'active');
        
        document.getElementById('active-now-count').textContent = activeRows.length;
        
        // Count rows with location (simplified - assumes active rows have location)
        document.getElementById('with-location-count').textContent = activeRows.length;
    }
    
    searchInput.addEventListener('input', filterEmployees);
    departmentFilter.addEventListener('change', filterEmployees);
    statusFilter.addEventListener('change', filterEmployees);
    
    // Initial stats update
    updateStats();
    
    // Load active employees count from API
    loadActiveCount();
});

function getLocation(employeeId) {
    fetch(`/live-tracking/employee/${employeeId}/location`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(`Employee: ${data.employee.name}\nLocation: ${data.location.address}\nUpdated: ${data.location.updated_at}`);
            } else {
                alert('Location not available');
            }
        });
}

function refreshData() {
    showLoading();
    // Simulate refresh
    setTimeout(() => {
        loadActiveCount();
        hideLoading();
        showAlert('Data refreshed successfully!', 'success');
    }, 1000);
}

function loadActiveCount() {
    fetch('{{ route("live-tracking.active-employees") }}')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('active-now-count').textContent = data.count;
            }
        });
}

function showLoading() {
    const spinner = document.getElementById('loading-spinner');
    if (spinner) spinner.classList.remove('hidden');
}

function hideLoading() {
    const spinner = document.getElementById('loading-spinner');
    if (spinner) spinner.classList.add('hidden');
}

function showAlert(message, type = 'success') {
    const alert = document.createElement('div');
    alert.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
        type === 'success' ? 'bg-green-100 text-green-800 border border-green-200' : 
        'bg-red-100 text-red-800 border border-red-200'
    }`;
    alert.innerHTML = `
        <div class="flex items-center">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-2"></i>
            ${message}
        </div>
    `;
    
    document.body.appendChild(alert);
    
    setTimeout(() => {
        alert.remove();
    }, 3000);
}
</script>
@endsection