@extends('layouts.dashboard')

@section('title', 'Payroll Management')

@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">Payroll Management</h1>
            <p class="text-gray-600 mt-1">Manage employee salaries and payments</p>
        </div>
        <div class="flex flex-wrap items-center gap-3 mt-4 md:mt-0">
            <button onclick="showGenerateModal()" 
                    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-calculator mr-2"></i> Generate Payrolls
            </button>
            <a href="{{ route('admin.payrolls.create') }}" 
               class="inline-flex items-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-plus-circle mr-2"></i> Create Payroll
            </a>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5 mb-8">
        <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">
                <div class="p-3 rounded-xl bg-blue-50 text-blue-600">
                    <i class="fas fa-file-invoice-dollar text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Total Payrolls</p>
                    <p class="text-2xl font-bold text-gray-900 mt-1">{{ $payrolls->total() }}</p>
                </div>
            </div>
            <div class="mt-4 pt-4 border-t border-gray-100">
                <span class="text-xs font-medium text-gray-600">
                    <i class="fas fa-users mr-1"></i> {{ \App\Models\User::role('employee')->count() }} employees
                </span>
            </div>
        </div>

        <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">
                <div class="p-3 rounded-xl bg-amber-50 text-amber-600">
                    <i class="fas fa-clock text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Draft</p>
                    <p class="text-2xl font-bold text-gray-900 mt-1">
                        {{ \App\Models\Payroll::where('status', 'draft')->count() }}
                    </p>
                </div>
            </div>
            <div class="mt-4 pt-4 border-t border-gray-100">
                <span class="text-xs font-medium text-amber-600 bg-amber-50 px-2 py-1 rounded-full">
                    <i class="fas fa-pencil-alt mr-1"></i> Pending
                </span>
            </div>
        </div>

        <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">
                <div class="p-3 rounded-xl bg-emerald-50 text-emerald-600">
                    <i class="fas fa-check-circle text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Processed</p>
                    <p class="text-2xl font-bold text-gray-900 mt-1">
                        {{ \App\Models\Payroll::where('status', 'processed')->count() }}
                    </p>
                </div>
            </div>
            <div class="mt-4 pt-4 border-t border-gray-100">
                <span class="text-xs font-medium text-emerald-600 bg-emerald-50 px-2 py-1 rounded-full">
                    <i class="fas fa-cogs mr-1"></i> Ready
                </span>
            </div>
        </div>

        <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">
                <div class="p-3 rounded-xl bg-purple-50 text-purple-600">
                    <i class="fas fa-money-check-alt text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Paid</p>
                    <p class="text-2xl font-bold text-gray-900 mt-1">
                        {{ \App\Models\Payroll::where('status', 'paid')->count() }}
                    </p>
                </div>
            </div>
            <div class="mt-4 pt-4 border-t border-gray-100">
                <span class="text-xs font-medium text-purple-600 bg-purple-50 px-2 py-1 rounded-full">
                    <i class="fas fa-check mr-1"></i> Completed
                </span>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 mb-6">
        <div class="flex flex-wrap items-center gap-4">
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">Status</label>
                <select class="px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 bg-white text-sm"
                        id="statusFilter">
                    <option value="">All Status</option>
                    <option value="draft">Draft</option>
                    <option value="processed">Processed</option>
                    <option value="paid">Paid</option>
                </select>
            </div>
            
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">Employee</label>
                <select class="px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 bg-white text-sm"
                        id="employeeFilter">
                    <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>
                <label class="block text-xs font-medium text-gray-700 mb-1">Month</label>
                <input type="month" 
                       class="px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 bg-white text-sm"
                       id="monthFilter" 
                       value="{{ date('Y-m') }}">
            </div>
            
            <div class="flex items-end gap-2">
                <button class="mt-6 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"
                        onclick="applyFilters()">
                    <i class="fas fa-filter mr-2"></i> Filter
                </button>
                
                <button class="mt-6 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"
                        onclick="resetFilters()">
                    <i class="fas fa-redo mr-2"></i> Reset
                </button>
            </div>
        </div>
    </div>

    <!-- Payrolls Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 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.5 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-user mr-2"></i> Employee & Period
                            </div>
                        </th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-money-bill-wave mr-2"></i> Salary Details
                            </div>
                        </th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-calendar mr-2"></i> Payment
                            </div>
                        </th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-info-circle mr-2"></i> Status
                            </div>
                        </th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-cog mr-2"></i> Actions
                            </div>
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @forelse($payrolls as $payroll)
                    <tr class="hover:bg-gray-50 transition-colors duration-150">
                        <td class="px-6 py-4">
                            <div class="flex items-center">
                                <div class="flex-shrink-0">
                                    <div class="h-10 w-10 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-sm">
                                        <i class="fas fa-user text-white"></i>
                                    </div>
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-semibold text-gray-900">{{ $payroll->employee->name }}</div>
                                    <div class="text-sm text-gray-500 flex items-center">
                                        <i class="fas fa-id-card text-gray-400 mr-1.5 text-xs"></i>
                                        {{ $payroll->employee->employee_id }}
                                    </div>
                                    <div class="text-xs text-gray-400 flex items-center mt-1">
                                        <i class="fas fa-calendar-alt text-gray-400 mr-1.5"></i>
                                        {{ $payroll->pay_period_start->format('M d') }} - {{ $payroll->pay_period_end->format('M d, Y') }}
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900">
                                <div class="flex items-center justify-between mb-1">
                                    <span class="text-gray-600">Basic:</span>
                                    <span class="font-medium">{{ number_format($payroll->basic_salary, 2) }} EGP</span>
                                </div>
                                <div class="flex items-center justify-between text-xs">
                                    <span class="text-gray-500">Allowances:</span>
                                    <span class="text-emerald-600 font-medium">+{{ number_format($payroll->allowances, 2) }}</span>
                                </div>
                                <div class="flex items-center justify-between text-xs">
                                    <span class="text-gray-500">Deductions:</span>
                                    <span class="text-red-600 font-medium">-{{ number_format($payroll->deductions, 2) }}</span>
                                </div>
                                <div class="mt-2 pt-2 border-t border-gray-200">
                                    <div class="flex items-center justify-between">
                                        <span class="font-semibold">Net Salary:</span>
                                        <span class="font-bold text-lg text-blue-600">{{ number_format($payroll->net_salary, 2) }} EGP</span>
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900">
                                @if($payroll->payment_date)
                                <div class="flex items-center">
                                    <i class="fas fa-calendar-check text-gray-400 mr-2"></i>
                                    <span class="font-medium">{{ $payroll->payment_date->format('M d, Y') }}</span>
                                </div>
                                @else
                                <div class="text-gray-500 flex items-center">
                                    <i class="fas fa-calendar-times text-gray-400 mr-2"></i>
                                    Not scheduled
                                </div>
                                @endif
                                
                                @if($payroll->processed_at)
                                <div class="text-xs text-gray-500 mt-2 flex items-center">
                                    <i class="fas fa-cogs text-gray-400 mr-1.5"></i>
                                    Processed: {{ $payroll->processed_at->format('M d, h:i A') }}
                                </div>
                                @endif
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            @php
                                $statusColors = [
                                    'draft' => 'bg-amber-100 text-amber-800',
                                    'processed' => 'bg-blue-100 text-blue-800',
                                    'paid' => 'bg-emerald-100 text-emerald-800'
                                ];
                                
                                $statusIcons = [
                                    'draft' => 'fa-clock',
                                    'processed' => 'fa-check-circle',
                                    'paid' => 'fa-money-check-alt'
                                ];
                            @endphp
                            <span class="inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium {{ $statusColors[$payroll->status] }}">
                                <i class="fas {{ $statusIcons[$payroll->status] }} mr-1.5"></i>
                                {{ ucfirst($payroll->status) }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <div class="flex items-center space-x-2">
                                <a href="{{ route('payrolls.show', $payroll) }}" 
                                   class="text-blue-600 hover:text-blue-800 hover:bg-blue-50 p-2 rounded-lg transition-colors duration-200"
                                   title="View Details">
                                    <i class="fas fa-eye text-sm"></i>
                                </a>
                                
                                @if($payroll->status == 'draft')
                                <a href="{{ route('payrolls.edit', $payroll) }}" 
                                   class="text-amber-600 hover:text-amber-800 hover:bg-amber-50 p-2 rounded-lg transition-colors duration-200"
                                   title="Edit">
                                    <i class="fas fa-edit text-sm"></i>
                                </a>
                                
                                <form action="{{ route('payrolls.process', $payroll) }}" 
                                      method="POST" 
                                      class="inline">
                                    @csrf
                                    <button type="submit" 
                                            class="text-emerald-600 hover:text-emerald-800 hover:bg-emerald-50 p-2 rounded-lg transition-colors duration-200"
                                            title="Process"
                                            onclick="return confirm('Process this payroll?')">
                                        <i class="fas fa-check text-sm"></i>
                                    </button>
                                </form>
                                
                                <form action="{{ route('payrolls.destroy', $payroll) }}" 
                                      method="POST" 
                                      class="inline"
                                      onsubmit="return confirmDelete()">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" 
                                            class="text-red-600 hover:text-red-800 hover:bg-red-50 p-2 rounded-lg transition-colors duration-200"
                                            title="Delete">
                                        <i class="fas fa-trash text-sm"></i>
                                    </button>
                                </form>
                                @endif
                                
                                @if($payroll->status == 'processed')
                                <form action="{{ route('payrolls.mark-paid', $payroll) }}" 
                                      method="POST" 
                                      class="inline">
                                    @csrf
                                    <button type="submit" 
                                            class="text-purple-600 hover:text-purple-800 hover:bg-purple-50 p-2 rounded-lg transition-colors duration-200"
                                            title="Mark as Paid"
                                            onclick="return confirm('Mark this payroll as paid?')">
                                        <i class="fas fa-money-check-alt text-sm"></i>
                                    </button>
                                </form>
                                @endif
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="5" class="px-6 py-12 text-center">
                            <div class="flex flex-col items-center justify-center">
                                <div class="w-20 h-20 mb-4 text-gray-300">
                                    <i class="fas fa-file-invoice-dollar text-5xl"></i>
                                </div>
                                <h3 class="text-lg font-semibold text-gray-700 mb-2">No Payrolls Found</h3>
                                <p class="text-gray-500 mb-6 max-w-md mx-auto">You haven't created any payrolls yet. Get started by creating payroll records for your employees.</p>
                                <div class="flex items-center gap-3">
                                    <a href="{{ route('admin.payrolls.create') }}" 
                                       class="inline-flex items-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-plus-circle mr-2"></i> Create Payroll
                                    </a>
                                    <button onclick="showGenerateModal()" 
                                            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-calculator mr-2"></i> Generate Payrolls
                                    </button>
                                </div>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if($payrolls->hasPages())
        <div class="bg-gray-50 px-6 py-4 border-t border-gray-100">
            {{ $payrolls->links() }}
        </div>
        @endif
    </div>
</div>

<!-- Generate Payrolls Modal -->
<div id="generateModal" 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-1/2 lg:w-1/3 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">Generate Payrolls</h3>
                <p class="text-sm text-gray-600 mt-1">Generate payrolls for multiple employees</p>
            </div>
            <button onclick="closeGenerateModal()" 
                    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>
        
        <form action="{{ route('payrolls.generate') }}" method="POST" id="generateForm">
            @csrf
            
            <div class="space-y-6">
                <!-- Month Selection -->
                <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>For Month *
                    </label>
                    <input type="month" 
                           name="month" 
                           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') }}"
                           required>
                </div>
                
                <!-- Employee Selection -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-users mr-2 text-blue-500"></i>Select Employees
                    </label>
                    <div class="mt-2 space-y-3 max-h-64 overflow-y-auto border border-gray-200 rounded-lg p-4">
                        <div class="flex items-center mb-2">
                            <input type="checkbox" 
                                   id="selectAll"
                                   class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                   checked>
                            <label for="selectAll" class="ml-2 text-sm font-medium text-gray-700">
                                Select All Employees
                            </label>
                        </div>
                        
                        <div class="border-t border-gray-200 pt-3">
                            @foreach(\App\Models\User::role('employee')->where('status', 'active')->get() as $employee)
                            <label class="flex items-center mb-3 hover:bg-gray-50 p-2 rounded-lg transition duration-150">
                                <input type="checkbox" 
                                       name="employee_ids[]" 
                                       value="{{ $employee->id }}"
                                       class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded employee-checkbox"
                                       checked>
                                <div class="ml-3">
                                    <span class="text-sm font-medium text-gray-700">{{ $employee->name }}</span>
                                    <div class="flex items-center text-xs text-gray-500 mt-1">
                                        <span class="mr-3">
                                            <i class="fas fa-id-card mr-1"></i> {{ $employee->employee_id }}
                                        </span>
                                        @if($employee->department)
                                        <span>
                                            <i class="fas fa-building mr-1"></i> {{ $employee->department->name }}
                                        </span>
                                        @endif
                                    </div>
                                </div>
                            </label>
                            @endforeach
                        </div>
                    </div>
                    <p class="mt-3 text-sm text-gray-500 flex items-center">
                        <i class="fas fa-info-circle mr-2 text-blue-500"></i>
                        Leave unchecked to generate for all active employees
                    </p>
                </div>
                
                <!-- Notes -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-sticky-note mr-2 text-blue-500"></i>Notes (Optional)
                    </label>
                    <textarea name="notes" 
                              rows="3"
                              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"
                              placeholder="Any special instructions or notes..."></textarea>
                </div>
            </div>
            
            <div class="mt-8 pt-6 border-t border-gray-200 flex justify-end space-x-3">
                <button type="button" 
                        onclick="closeGenerateModal()" 
                        class="px-4 py-2.5 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition duration-200">
                    Cancel
                </button>
                <button type="submit" 
                        class="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-calculator mr-2"></i> Generate Payrolls
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function confirmDelete() {
    return confirm('Are you sure you want to delete this payroll? This action cannot be undone.');
}

function showGenerateModal() {
    const modal = document.getElementById('generateModal');
    modal.classList.remove('hidden');
    setTimeout(() => {
        modal.style.opacity = '1';
    }, 10);
}

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

// Select all employees functionality
document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const employeeCheckboxes = document.querySelectorAll('.employee-checkbox');
    
    selectAllCheckbox.addEventListener('change', function() {
        employeeCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });
    
    // Check if all employees are selected
    employeeCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const allChecked = Array.from(employeeCheckboxes).every(cb => cb.checked);
            const someChecked = Array.from(employeeCheckboxes).some(cb => cb.checked);
            
            selectAllCheckbox.checked = allChecked;
            selectAllCheckbox.indeterminate = someChecked && !allChecked;
        });
    });
});

// Close modal when clicking outside
document.getElementById('generateModal')?.addEventListener('click', function(e) {
    if (e.target.id === 'generateModal') {
        closeGenerateModal();
    }
});

function applyFilters() {
    const status = document.getElementById('statusFilter').value;
    const employee = document.getElementById('employeeFilter').value;
    const month = document.getElementById('monthFilter').value;
    
    let url = new URL(window.location.href);
    let params = new URLSearchParams(url.search);
    
    if (status) params.set('status', status);
    if (employee) params.set('employee_id', employee);
    if (month) params.set('month', month);
    
    window.location.href = url.pathname + '?' + params.toString();
}

function resetFilters() {
    window.location.href = window.location.pathname;
}
</script>

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

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

/* Custom scrollbar for employee list */
.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;
}
</style>
@endsection