<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payroll Dashboard</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">
    <style>
        .quickbooks-table { border-collapse: separate; border-spacing: 0; width: 100%; }
        .quickbooks-table th { background-color: #F3F2F1; color: #323130; font-weight: 600; font-size: 13px; text-transform: uppercase; padding: 12px 16px; border-bottom: 1px solid #EDEBE9; text-align: left; }
        .quickbooks-table td { padding: 12px 16px; border-bottom: 1px solid #EDEBE9; font-size: 14px; color: #323130; }
        .quickbooks-table tbody tr:hover { background-color: #F3F2F1; }
        .quickbooks-input { border: 1px solid #8C8C8C; border-radius: 4px; padding: 6px 12px; font-size: 14px; }
        .quickbooks-input:focus { outline: 2px solid #146CAA; outline-offset: -1px; border-color: #146CAA; }
        .quickbooks-badge { display: inline-flex; align-items: center; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 600; }
        .action-btn { width: 32px; height: 32px; border-radius: 4px; display: inline-flex; align-items: center; justify-content: center; margin: 0 2px; transition: all 0.2s; }
        .action-btn:hover { transform: translateY(-1px); }
        .action-btn-edit { background-color: #E1F0FA; color: #146CAA; }
        .action-btn-edit:hover { background-color: #146CAA; color: white; }
        .action-btn-delete { background-color: #FEE; color: #D83B01; }
        .action-btn-delete:hover { background-color: #D83B01; color: white; }
        .action-btn-view { background-color: #F3F2F1; color: #323130; }
        .action-btn-view:hover { background-color: #146CAA; color: white; }
        .modal-backdrop { background-color: rgba(0, 0, 0, 0.5); }
        .modal-content { max-height: 90vh; overflow-y: auto; }
        .modal-section { border-top: 1px solid #EDEBE9; padding-top: 24px; margin-top: 24px; }
        .modal-divider { border-top: 1px solid #EDEBE9; margin: 20px 0; }
        .modal-info { background-color: #F3F2F1; border: 1px solid #EDEBE9; border-radius: 4px; padding: 12px; margin-top: 8px; font-size: 13px; color: #605E5C; }
        .modal-info i { color: #605E5C; margin-right: 8px; }
        .stat-card { transition: all 0.3s ease; }
        .stat-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
        .status-badge { padding: 4px 8px; border-radius: 12px; font-size: 11px; font-weight: 600; }
        .status-open { background-color: #D1FAE5; color: #065F46; }
        .status-closed { background-color: #F3F4F6; color: #374151; }
        .status-processing { background-color: #FEF3C7; color: #92400E; }
    </style>
</head>
<body class="bg-gray50">
    @include('accounting.partials.sidebar')

    <div class="lg:ml-64">
        @include('accounting.partials.header', ['title' => 'Payroll Management', 'subtitle' => 'Manage payroll settings and periods'])

        <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">
                    <div class="flex items-center">
                        <i class="fas fa-check-circle text-green-500 mr-2"></i>
                        <span class="text-green-800 font-semibold">{{ session('success') }}</span>
                    </div>
                </div>
            @endif

            @if(session('error'))
                <div class="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                        <span class="text-red-800 font-semibold">{{ session('error') }}</span>
                    </div>
                </div>
            @endif

            <!-- Company Info Banner -->
            <div class="mb-8 bg-white rounded-lg border border-gray200 p-6">
                <div class="flex flex-col md:flex-row md:items-center justify-between">
                    <div>
                        <h2 class="text-xl font-semibold text-gray900">{{ $company->name }}</h2>
                        <p class="text-gray600 text-sm mt-1">
                            Current Financial Year: 
                            <span class="font-medium">{{ $currentFinancialYear->year ?? 'Not Set' }}</span>
                            @if($currentFinancialYear)
                                <span class="text-gray500 ml-2">
                                    ({{ $currentFinancialYear->start_date->format('M d, Y') }} - {{ $currentFinancialYear->end_date->format('M d, Y') }})
                                </span>
                            @endif
                        </p>
                    </div>
                    <div class="mt-4 md:mt-0">
                        <span class="quickbooks-badge bg-blue-100 text-blue-800">Payroll Management</span>
                    </div>
                </div>
            </div>

            <!-- Stats Cards -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                <!-- PAYE Settings Card -->
                <a href="{{ route('admin.accounting.payroll.paye.index') }}" 
                   class="stat-card bg-white rounded-lg border border-gray200 p-6 hover:shadow-lg hover:border-primary transition-all">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center mr-4">
                            <i class="fas fa-percentage text-red-500 text-xl"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray600 mb-1">PAYE Tax Bands</p>
                            <p class="text-xl font-semibold text-gray900">
                                @if($payeSettings && $payeSettings->payeTaxBands->count() > 0)
                                    <span class="text-green-600">{{ $payeSettings->payeTaxBands->count() }} Bands</span>
                                @else
                                    <span class="text-red-600">Not Set</span>
                                @endif
                            </p>
                            <p class="text-xs text-gray500 mt-1">
                                @if($payeSettings)
                                    {{ $payeSettings->year }}
                                @else
                                    Requires setup
                                @endif
                            </p>
                        </div>
                    </div>
                    <div class="mt-4">
                        <div class="flex items-center justify-between text-xs">
                            <span class="text-gray500">Status:</span>
                            @if($payeSettings)
                                <span class="status-badge status-open">Configured</span>
                            @else
                                <span class="status-badge status-closed">Not Configured</span>
                            @endif
                        </div>
                    </div>
                </a>

                <!-- NAPSA Card -->
                <a href="{{ route('admin.accounting.payroll.napsa.index') }}" 
                   class="stat-card bg-white rounded-lg border border-gray200 p-6 hover:shadow-lg hover:border-primary transition-all">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center mr-4">
                            <i class="fas fa-shield-alt text-blue-500 text-xl"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray600 mb-1">NAPSA</p>
                            <p class="text-xl font-semibold text-gray900">
                                @if($napsaSettings)
                                    <span class="text-green-600">{{ $napsaSettings->monthly_rate }}%</span>
                                @else
                                    <span class="text-red-600">Not Set</span>
                                @endif
                            </p>
                            <p class="text-xs text-gray500 mt-1">
                                @if($napsaSettings)
                                    Ceiling: K{{ number_format($napsaSettings->monthly_ceiling, 2) }}/month
                                @else
                                    Requires setup
                                @endif
                            </p>
                        </div>
                    </div>
                    <div class="mt-4">
                        <div class="flex items-center justify-between text-xs">
                            <span class="text-gray500">Status:</span>
                            @if($napsaSettings)
                                <span class="status-badge status-open">Active</span>
                            @else
                                <span class="status-badge status-closed">Not Set</span>
                            @endif
                        </div>
                    </div>
                </a>

                <!-- NHIMA Card -->
                <a href="{{ route('admin.accounting.payroll.nhima.index') }}" 
                   class="stat-card bg-white rounded-lg border border-gray200 p-6 hover:shadow-lg hover:border-primary transition-all">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center mr-4">
                            <i class="fas fa-heartbeat text-green-500 text-xl"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray600 mb-1">NHIMA</p>
                            <p class="text-xl font-semibold text-gray900">
                                @if($nhimaSettings)
                                    <span class="text-green-600">{{ $nhimaSettings->monthly_rate }}%</span>
                                @else
                                    <span class="text-red-600">Not Set</span>
                                @endif
                            </p>
                            <p class="text-xs text-gray500 mt-1">
                                {{ $nhimaSettings ? 'Current rate' : 'Requires setup' }}
                            </p>
                        </div>
                    </div>
                    <div class="mt-4">
                        <div class="flex items-center justify-between text-xs">
                            <span class="text-gray500">Status:</span>
                            @if($nhimaSettings)
                                <span class="status-badge status-open">Active</span>
                            @else
                                <span class="status-badge status-closed">Not Set</span>
                            @endif
                        </div>
                    </div>
                </a>

                <!-- Payroll Periods Card -->
                <a href="{{ route('admin.accounting.payroll.periods.index') }}" 
                   class="stat-card bg-white rounded-lg border border-gray200 p-6 hover:shadow-lg hover:border-primary transition-all">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center mr-4">
                            <i class="fas fa-calendar-alt text-purple-500 text-xl"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray600 mb-1">Payroll Periods</p>
                            <p class="text-xl font-semibold text-gray900">{{ $payrollPeriods->total() }}</p>
                            <p class="text-xs text-gray500 mt-1">
                                {{ $payrollPeriods->where('status', 'open')->count() }} Open
                            </p>
                        </div>
                    </div>
                    <div class="mt-4">
                        <div class="flex items-center justify-between text-xs">
                            <span class="text-gray500">Current:</span>
                            @php
                                $currentPeriod = $payrollPeriods->where('status', 'open')->first();
                            @endphp
                            @if($currentPeriod)
                                <span class="font-medium">{{ $currentPeriod->month_name }}</span>
                            @else
                                <span class="text-gray500">No open periods</span>
                            @endif
                        </div>
                    </div>
                </a>
            </div>

            <!-- Quick Actions -->
            <div class="mb-8 bg-white rounded-lg border border-gray200 p-6">
                <h3 class="text-lg font-semibold text-gray900 mb-4">Quick Actions</h3>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <a href="{{ route('admin.accounting.payroll.paye.index') }}" 
                       class="bg-gray50 hover:bg-gray100 border border-gray200 rounded-lg p-4 flex items-center transition-colors">
                        <div class="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-percentage text-red-500"></i>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray900">Setup PAYE</p>
                            <p class="text-xs text-gray500">Configure tax bands</p>
                        </div>
                    </a>
                    
                    <a href="{{ route('admin.accounting.payroll.napsa.index') }}" 
                       class="bg-gray50 hover:bg-gray100 border border-gray200 rounded-lg p-4 flex items-center transition-colors">
                        <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-shield-alt text-blue-500"></i>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray900">Setup NAPSA</p>
                            <p class="text-xs text-gray500">Configure rates</p>
                        </div>
                    </a>
                    
                    <a href="{{ route('admin.accounting.payroll.nhima.index') }}" 
                       class="bg-gray50 hover:bg-gray100 border border-gray200 rounded-lg p-4 flex items-center transition-colors">
                        <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-heartbeat text-green-500"></i>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray900">Setup NHIMA</p>
                            <p class="text-xs text-gray500">Configure rates</p>
                        </div>
                    </a>
                    
                    <a href="{{ route('admin.accounting.payroll.periods.index') }}" 
                       class="bg-gray50 hover:bg-gray100 border border-gray200 rounded-lg p-4 flex items-center transition-colors">
                        <div class="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-calendar-plus text-purple-500"></i>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray900">Create Period</p>
                            <p class="text-xs text-gray500">Add payroll period</p>
                        </div>
                    </a>
                </div>
            </div>

            <!-- PAYE Calculator -->
            <div class="bg-white rounded-lg border border-gray200 p-6 mb-8">
                <div class="flex items-center justify-between mb-6">
                    <div>
                        <h3 class="text-lg font-semibold text-gray900">PAYE Calculator</h3>
                        <p class="text-gray600 text-sm">Calculate PAYE tax for monthly salary</p>
                    </div>
                    <div class="text-sm text-gray500">
                        Based on {{ $currentFinancialYear->year ?? 'Current' }} tax bands
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Calculator Input -->
                    <div>
                        <label class="block text-sm font-medium text-gray700 mb-2">Monthly Salary (ZMW)</label>
                        <div class="flex space-x-3">
                            <div class="relative flex-1">
                                <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray500">K</span>
                                <input type="number" 
                                       id="monthlySalary" 
                                       class="quickbooks-input w-full pl-8" 
                                       placeholder="Enter monthly salary" 
                                       min="0" 
                                       step="0.01">
                            </div>
                            <button onclick="calculatePAYE()" 
                                    class="bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90">
                                Calculate
                            </button>
                        </div>
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray700 mb-2">Financial Year</label>
                            <select id="financialYear" class="quickbooks-input w-full">
                                @if($currentFinancialYear)
                                    <option value="{{ $currentFinancialYear->id }}">{{ $currentFinancialYear->year }}</option>
                                @endif
                                @foreach($company->financialYears->where('id', '!=', $currentFinancialYear->id ?? null) as $year)
                                    <option value="{{ $year->id }}">{{ $year->year }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mt-4">
                            <p class="text-sm text-gray600">
                                <i class="fas fa-info-circle mr-1"></i>
                                Calculator uses the configured tax bands for the selected financial year.
                            </p>
                        </div>
                    </div>

                    <!-- Results Display -->
                    <div>
                        <div id="calculationResult" class="hidden bg-gray50 border border-gray200 rounded-lg p-4">
                            <h4 class="text-sm font-semibold text-gray900 mb-3">PAYE Calculation</h4>
                            
                            <div class="space-y-3">
                                <div class="flex justify-between">
                                    <span class="text-gray600">Monthly Salary:</span>
                                    <span id="resultSalary" class="font-semibold text-gray900"></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray600">Total PAYE Tax:</span>
                                    <span id="resultTax" class="font-semibold text-red-600"></span>
                                </div>
                                <div class="border-t border-gray200 pt-2">
                                    <div class="flex justify-between">
                                        <span class="text-gray600">Net Salary:</span>
                                        <span id="resultNet" class="font-semibold text-green-600 text-lg"></span>
                                    </div>
                                </div>
                            </div>

                            <!-- Band Breakdown -->
                            <div id="bandBreakdown" class="mt-4 hidden">
                                <h5 class="text-sm font-medium text-gray700 mb-2">Tax Band Breakdown</h5>
                                <div class="bg-white border border-gray200 rounded p-3">
                                    <table class="w-full text-sm">
                                        <thead>
                                            <tr class="text-xs text-gray500">
                                                <th class="text-left pb-2">Band</th>
                                                <th class="text-left pb-2">Range</th>
                                                <th class="text-left pb-2">Taxable</th>
                                                <th class="text-left pb-2">Tax</th>
                                            </tr>
                                        </thead>
                                        <tbody id="bandDetails">
                                            <!-- Band details will be populated here -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- No Settings Message -->
                        <div id="noSettingsMessage" class="hidden bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                            <div class="flex items-center">
                                <i class="fas fa-exclamation-triangle text-yellow-500 mr-2"></i>
                                <span class="text-yellow-800 font-medium">No PAYE settings found for the selected financial year.</span>
                            </div>
                            <div class="mt-2">
                                <a href="{{ route('admin.accounting.payroll.paye.index') }}" 
                                   class="text-primary hover:text-primary/90 text-sm font-medium">
                                    Setup PAYE Bands →
                                </a>
                            </div>
                        </div>

                        <!-- Loading State -->
                        <div id="loadingState" class="hidden bg-gray50 border border-gray200 rounded-lg p-8 text-center">
                            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
                            <p class="text-sm text-gray600">Calculating...</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Payroll Periods -->
            <div class="bg-white rounded-lg border border-gray200">
                <div class="border-b border-gray200 p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <h3 class="text-lg font-semibold text-gray900">Recent Payroll Periods</h3>
                            <p class="text-gray600 text-sm">Latest payroll periods for {{ $currentFinancialYear->year ?? 'Current Year' }}</p>
                        </div>
                        <a href="{{ route('admin.accounting.payroll.periods.index') }}" 
                           class="text-primary hover:text-primary/90 text-sm font-medium">
                            View All
                        </a>
                    </div>
                </div>

                <div class="overflow-x-auto">
                    <table class="quickbooks-table">
                        <thead>
                            <tr>
                                <th>Period Name</th>
                                <th>Date Range</th>
                                <th>Payment Date</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($payrollPeriods->take(5) as $period)
                                <tr>
                                    <td class="font-medium text-gray900">{{ $period->period_name }}</td>
                                    <td>
                                        <div class="text-gray700">{{ $period->formatted_date_range }}</div>
                                        <div class="text-xs text-gray500">
                                            Cutoff: {{ $period->cutoff_date->format('M d, Y') }}
                                        </div>
                                    </td>
                                    <td class="text-gray700">{{ $period->payment_date->format('M d, Y') }}</td>
                                    <td>
                                        @if($period->status === 'open')
                                            <span class="status-badge status-open">Open</span>
                                        @elseif($period->status === 'closed')
                                            <span class="status-badge status-closed">Closed</span>
                                        @else
                                            <span class="status-badge status-processing">Processing</span>
                                        @endif
                                    </td>
                                    <td>
                                        <div class="flex items-center">
                                            <a href="{{ route('admin.accounting.payroll.periods.index') }}?edit={{ $period->id }}" 
                                               class="action-btn action-btn-edit"
                                               title="Edit period">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            @if($period->canProcessPayroll())
                                                <button onclick="processPayroll({{ $period->id }})" 
                                                        class="action-btn action-btn-view ml-2"
                                                        title="Process payroll">
                                                    <i class="fas fa-cogs"></i>
                                                </button>
                                            @endif
                                            @if($period->status === 'closed')
                                                <button onclick="reopenPeriod({{ $period->id }})" 
                                                        class="action-btn action-btn-view ml-2 bg-green-100 text-green-600 hover:bg-green-600 hover:text-white"
                                                        title="Reopen period">
                                                    <i class="fas fa-redo"></i>
                                                </button>
                                            @endif
                                            @if($period->status === 'open')
                                                <button onclick="closePeriod({{ $period->id }})" 
                                                        class="action-btn action-btn-view ml-2 bg-red-100 text-red-600 hover:bg-red-600 hover:text-white"
                                                        title="Close period">
                                                    <i class="fas fa-lock"></i>
                                                </button>
                                            @endif
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="5" class="text-center py-8">
                                        <div class="py-8 text-center">
                                            <div class="w-16 h-16 bg-gray100 rounded-full flex items-center justify-center mx-auto mb-4">
                                                <i class="fas fa-calendar text-gray500 text-2xl"></i>
                                            </div>
                                            <h3 class="text-lg font-medium text-gray900 mb-2">No payroll periods</h3>
                                            <p class="text-gray600 mb-4 max-w-md mx-auto">Create your first payroll period to get started.</p>
                                            <a href="{{ route('admin.accounting.payroll.periods.index') }}" 
                                               class="inline-flex items-center text-primary hover:text-primary/90 font-medium">
                                                <i class="fas fa-plus mr-2"></i>Create Payroll Period
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Settings Status -->
            <div class="mt-8 grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="bg-white rounded-lg border border-gray200 p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="text-lg font-semibold text-gray900">PAYE Status</h4>
                        @if($payeSettings)
                            <span class="status-badge status-open">Configured</span>
                        @else
                            <span class="status-badge status-closed">Not Configured</span>
                        @endif
                    </div>
                    <p class="text-sm text-gray600 mb-4">
                        @if($payeSettings)
                            {{ $payeSettings->payeTaxBands->count() }} tax bands configured for {{ $payeSettings->year }}
                        @else
                            No PAYE tax bands configured
                        @endif
                    </p>
                    <a href="{{ route('admin.accounting.payroll.paye.index') }}" 
                       class="text-primary hover:text-primary/90 text-sm font-medium">
                        @if($payeSettings)
                            Edit Settings →
                        @else
                            Setup Now →
                        @endif
                    </a>
                </div>

                <div class="bg-white rounded-lg border border-gray200 p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="text-lg font-semibold text-gray900">NAPSA Status</h4>
                        @if($napsaSettings)
                            <span class="status-badge status-open">Active</span>
                        @else
                            <span class="status-badge status-closed">Not Set</span>
                        @endif
                    </div>
                    <p class="text-sm text-gray600 mb-4">
                        @if($napsaSettings)
                            Rate: {{ $napsaSettings->monthly_rate }}% | Ceiling: K{{ number_format($napsaSettings->monthly_ceiling, 2) }}
                        @else
                            NAPSA rates not configured
                        @endif
                    </p>
                    <a href="{{ route('admin.accounting.payroll.napsa.index') }}" 
                       class="text-primary hover:text-primary/90 text-sm font-medium">
                        @if($napsaSettings)
                            Edit Settings →
                        @else
                            Setup Now →
                        @endif
                    </a>
                </div>

                <div class="bg-white rounded-lg border border-gray200 p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="text-lg font-semibold text-gray900">NHIMA Status</h4>
                        @if($nhimaSettings)
                            <span class="status-badge status-open">Active</span>
                        @else
                            <span class="status-badge status-closed">Not Set</span>
                        @endif
                    </div>
                    <p class="text-sm text-gray600 mb-4">
                        @if($nhimaSettings)
                            Rate: {{ $nhimaSettings->monthly_rate }}%
                        @else
                            NHIMA rates not configured
                        @endif
                    </p>
                    <a href="{{ route('admin.accounting.payroll.nhima.index') }}" 
                       class="text-primary hover:text-primary/90 text-sm font-medium">
                        @if($nhimaSettings)
                            Edit Settings →
                        @else
                            Setup Now →
                        @endif
                    </a>
                </div>
            </div>
        </main>
    </div>

    <!-- Process Payroll Modal -->
    <div id="processPayrollModal" class="fixed inset-0 bg-gray900 bg-opacity-50 hidden items-center justify-center z-50 p-4">
        <div class="bg-white rounded-lg shadow-lg max-w-md w-full">
            <div class="border-b border-gray200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <h2 class="text-xl font-semibold text-gray900">Process Payroll</h2>
                        <p class="text-gray600 text-sm">Process payroll for selected period</p>
                    </div>
                    <button onclick="closeProcessPayrollModal()" class="text-gray500 hover:text-gray700">
                        <i class="fas fa-times text-lg"></i>
                    </button>
                </div>
            </div>

            <div class="p-6">
                <div class="mb-4">
                    <p class="text-sm text-gray600" id="processPeriodName"></p>
                </div>
                
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray700 mb-2">Payment Method</label>
                        <select class="quickbooks-input w-full">
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="cash">Cash</option>
                            <option value="cheque">Cheque</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray700 mb-2">Payment Date</label>
                        <input type="date" class="quickbooks-input w-full" value="{{ date('Y-m-d') }}">
                    </div>
                    
                    <div class="flex items-center">
                        <input type="checkbox" id="generatePayslips" class="quickbooks-checkbox mr-2" checked>
                        <label for="generatePayslips" class="text-sm text-gray600">Generate payslips</label>
                    </div>
                    
                    <div class="flex items-center">
                        <input type="checkbox" id="sendNotifications" class="quickbooks-checkbox mr-2">
                        <label for="sendNotifications" class="text-sm text-gray600">Send email notifications</label>
                    </div>
                </div>
            </div>
            
            <div class="border-t border-gray200 p-6 flex justify-end space-x-3">
                <button onclick="closeProcessPayrollModal()" class="px-4 py-2 text-gray700 hover:bg-gray100 rounded text-sm font-medium">
                    Cancel
                </button>
                <button onclick="confirmProcessPayroll()" class="bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90">
                    Process Payroll
                </button>
            </div>
        </div>
    </div>

    <script>
        let currentProcessPeriodId = null;

        // PAYE Calculator
        function calculatePAYE() {
            const monthlySalary = document.getElementById('monthlySalary').value;
            const financialYearId = document.getElementById('financialYear').value;

            if (!monthlySalary || monthlySalary <= 0) {
                showNotification('Please enter a valid monthly salary', 'error');
                return;
            }

            // Show loading state
            document.getElementById('calculationResult').classList.add('hidden');
            document.getElementById('noSettingsMessage').classList.add('hidden');
            document.getElementById('loadingState').classList.remove('hidden');

            fetch('{{ route("admin.accounting.payroll.calculate-paye") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    monthly_salary: monthlySalary,
                    financial_year_id: financialYearId
                })
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('loadingState').classList.add('hidden');

                if (data.success) {
                    // Show results
                    document.getElementById('calculationResult').classList.remove('hidden');
                    document.getElementById('noSettingsMessage').classList.add('hidden');

                    document.getElementById('resultSalary').textContent = 'K' + data.monthly_salary;
                    document.getElementById('resultTax').textContent = 'K' + data.total_tax;
                    document.getElementById('resultNet').textContent = 'K' + data.net_salary;

                    // Show band breakdown if available
                    if (data.band_calculations && data.band_calculations.length > 0) {
                        const bandDetails = document.getElementById('bandDetails');
                        bandDetails.innerHTML = '';
                        
                        data.band_calculations.forEach(band => {
                            const row = document.createElement('tr');
                            row.className = 'border-b border-gray100 last:border-0';
                            row.innerHTML = `
                                <td class="py-2">${band.band}</td>
                                <td class="py-2">${band.range}</td>
                                <td class="py-2">K${band.taxable_amount}</td>
                                <td class="py-2">K${band.tax}</td>
                            `;
                            bandDetails.appendChild(row);
                        });
                        
                        document.getElementById('bandBreakdown').classList.remove('hidden');
                    } else {
                        document.getElementById('bandBreakdown').classList.add('hidden');
                    }
                } else {
                    // Show no settings message
                    document.getElementById('calculationResult').classList.add('hidden');
                    document.getElementById('noSettingsMessage').classList.remove('hidden');
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                document.getElementById('loadingState').classList.add('hidden');
                showNotification('Failed to calculate PAYE', 'error');
                console.error('Error:', error);
            });
        }

        // Period Management
        function processPayroll(periodId) {
            currentProcessPeriodId = periodId;
            
            // Get period name
            const periodRow = document.querySelector(`tr:has(button[onclick="processPayroll(${periodId})"])`);
            const periodName = periodRow?.querySelector('td:first-child')?.textContent || 'this period';
            
            document.getElementById('processPeriodName').textContent = `Processing payroll for: ${periodName}`;
            document.getElementById('processPayrollModal').classList.remove('hidden');
        }

        function closeProcessPayrollModal() {
            document.getElementById('processPayrollModal').classList.add('hidden');
            currentProcessPeriodId = null;
        }

        function confirmProcessPayroll() {
            showNotification('Processing payroll... This may take a few moments.', 'info');
            closeProcessPayrollModal();
            
            // Simulate processing
            setTimeout(() => {
                showNotification('Payroll processed successfully', 'success');
            }, 2000);
        }

        function closePeriod(periodId) {
            if (confirm('Are you sure you want to close this payroll period? This will prevent further changes.')) {
                fetch(`/admin/accounting/payroll/periods/${periodId}/close`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification('Period closed successfully', 'success');
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        showNotification(data.message || 'Failed to close period', 'error');
                    }
                })
                .catch(error => {
                    showNotification('Failed to close period', 'error');
                });
            }
        }

        function reopenPeriod(periodId) {
            if (confirm('Are you sure you want to reopen this payroll period?')) {
                fetch(`/admin/accounting/payroll/periods/${periodId}/reopen`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification('Period reopened successfully', 'success');
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        showNotification(data.message || 'Failed to reopen period', 'error');
                    }
                })
                .catch(error => {
                    showNotification('Failed to reopen period', 'error');
                });
            }
        }

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

            const colors = {
                success: 'bg-green-500',
                error: 'bg-red-500',
                info: 'bg-primary',
                warning: 'bg-yellow-500'
            };

            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);

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

        // Add animation styles
        if (!document.querySelector('style[data-payroll-dashboard]')) {
            const style = document.createElement('style');
            style.setAttribute('data-payroll-dashboard', 'true');
            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); }
                }
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
                .animate-fade-in {
                    animation: fadeIn 0.3s ease-out;
                }
                .animate-fade-out {
                    animation: fadeOut 0.3s ease-in;
                }
                .animate-spin {
                    animation: spin 1s linear infinite;
                }
            `;
            document.head.appendChild(style);
        }

        // Auto-calculate on Enter key in salary field
        document.getElementById('monthlySalary').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                calculatePAYE();
            }
        });

        // Auto-format salary input
        document.getElementById('monthlySalary').addEventListener('blur', function() {
            if (this.value) {
                this.value = parseFloat(this.value).toFixed(2);
            }
        });
    </script>
</body>
</html>