<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payroll Processing </title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#146CAA',
                        primaryLight: '#E1F0FA',
                        secondary: '#6b7280',
                        success: '#107C10',
                        warning: '#F68C1E',
                        danger: '#D83B01',
                        info: '#0078D4',
                        gray50: '#FAF9F8',
                        gray100: '#F3F2F1',
                        gray200: '#EDEBE9',
                        gray300: '#E1DFDD',
                        gray400: '#C8C6C4',
                        gray500: '#A19F9D',
                        gray600: '#605E5C',
                        gray700: '#323130',
                        gray800: '#201F1E',
                        gray900: '#000000'
                    }
                }
            }
        }
    </script>
    <style>
        .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-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-view {
            background-color: #F3F2F1;
            color: #323130;
        }
        .action-btn-view:hover {
            background-color: #146CAA;
            color: white;
        }
        .action-btn-approve {
            background-color: #E6F4EA;
            color: #107C10;
        }
        .action-btn-approve:hover {
            background-color: #107C10;
            color: white;
        }
        .action-btn-pay {
            background-color: #E1F0FA;
            color: #146CAA;
        }
        .action-btn-pay:hover {
            background-color: #146CAA;
            color: white;
        }
        .action-btn-export {
            background-color: #F3F2F1;
            color: #605E5C;
        }
        .action-btn-export:hover {
            background-color: #605E5C;
            color: white;
        }
    </style>
</head>
<body class="bg-gray50">
    @include('accounting.partials.sidebar')

    <div class="lg:ml-64">
        @include('accounting.partials.header', ['title' => 'Payroll Processing', 'subtitle' => 'Process and manage payroll runs'])

        <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

            <!-- Action Cards -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-white rounded-lg border border-gray200 p-4">
                    <div class="flex items-center">
                        <div class="w-10 h-10 bg-primaryLight rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-calculator text-primary text-lg"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray600">Total Entries</p>
                            <p class="text-xl font-semibold text-gray900">{{ $payrollEntries->total() ?? 0 }}</p>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg border border-gray200 p-4">
                    <div class="flex items-center">
                        <div class="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-clock text-warning text-lg"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray600">Calculated</p>
                            <p class="text-xl font-semibold text-gray900">
                                {{ $payrollEntries->where('calculation_status', 'calculated')->count() ?? 0 }}
                            </p>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg border border-gray200 p-4">
                    <div class="flex items-center">
                        <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-check-circle text-blue-600 text-lg"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray600">Approved</p>
                            <p class="text-xl font-semibold text-gray900">
                                {{ $payrollEntries->where('calculation_status', 'approved')->where('payment_status', 'pending')->count() ?? 0 }}
                            </p>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg border border-gray200 p-4">
                    <div class="flex items-center">
                        <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-money-check-alt text-success text-lg"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray600">Paid</p>
                            <p class="text-xl font-semibold text-gray900">
                                {{ $payrollEntries->where('payment_status', 'paid')->count() ?? 0 }}
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Action Bar -->
            <div class="bg-white rounded-lg border border-gray200 p-4 mb-6">
                <div class="flex flex-col md:flex-row md:items-center justify-between space-y-4 md:space-y-0">
                    <div>
                        <h2 class="text-lg font-semibold text-gray900">Payroll Entries</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>
                        @if(isset($title) && isset($description))
                            <p class="text-gray600 text-sm mt-1">
                                <span class="font-medium">{{ $title }}:</span> {{ $description }}
                            </p>
                        @endif
                    </div>
                    <div class="flex space-x-3">
                        <!-- Status Filter -->
                        <div class="relative">
                            <select id="statusFilter" onchange="filterByStatus(this.value)" class="border border-gray300 text-gray700 px-4 py-2 rounded text-sm font-medium hover:bg-gray50 appearance-none bg-white pr-8">
                                <option value="all" {{ $status == 'all' ? 'selected' : '' }}>All Status</option>
                                <option value="calculated" {{ $status == 'calculated' ? 'selected' : '' }}>Pending Review</option>
                                <option value="approved" {{ $status == 'approved' ? 'selected' : '' }}>Approved</option>
                                <option value="paid" {{ $status == 'paid' ? 'selected' : '' }}>Paid</option>
                            </select>
                            <i class="fas fa-chevron-down absolute right-3 top-3 text-gray-500 pointer-events-none"></i>
                        </div>
                        
                        <!-- View Open Periods -->
                        <a href="{{ route('admin.accounting.payroll.periods.index') }}" 
                           class="border border-gray300 text-gray700 px-4 py-2 rounded text-sm font-medium hover:bg-gray50 flex items-center">
                            <i class="fas fa-calendar-alt mr-2"></i>Open Periods
                        </a>
                        
                        <!-- Process New Payroll -->
                        <button onclick="processNewPayroll()" 
                                class="bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90 flex items-center">
                            <i class="fas fa-plus mr-2"></i>Process Payroll
                        </button>
                    </div>
                </div>
            </div>

            <!-- Payroll Entries Table -->
            <div class="bg-white rounded-lg border border-gray200 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="quickbooks-table">
                        <thead>
                            <tr>
                                <th>Employee</th>
                                <th>Payroll Period</th>
                                <th>Entry Date</th>
                                <th>Calculation Status</th>
                                <th>Payment Status</th>
                                <th>Gross Earnings</th>
                                <th>Total Deductions</th>
                                <th>Net Pay</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($payrollEntries as $entry)
                                @php
                                    $employee = $entry->employee;
                                    $period = $entry->payrollPeriod;
                                    $run = $entry->payrollRun;
                                @endphp
                                <tr class="hover:bg-gray100 transition-colors">
                                    <td>
                                        <div class="font-medium text-gray900">{{ $employee->full_name ?? 'N/A' }}</div>
                                        <div class="text-xs text-gray500">{{ $employee->employee_number ?? '' }}</div>
                                    </td>
                                    <td>
                                        <div class="font-medium text-gray900">{{ $period->period_name ?? 'N/A' }}</div>
                                        <div class="text-xs text-gray500">{{ $period->formatted_date_range ?? 'N/A' }}</div>
                                    </td>
                                    <td class="text-gray700">
                                        {{ $entry->entry_date ? \Carbon\Carbon::parse($entry->entry_date)->format('M d, Y') : 'N/A' }}
                                    </td>
                                    <td>
                                        @php
                                            $calcStatusColors = [
                                                'draft' => 'bg-gray-100 text-gray-800',
                                                'processing' => 'bg-yellow-100 text-yellow-800',
                                                'calculated' => 'bg-blue-100 text-blue-800',
                                                'approved' => 'bg-green-100 text-green-800'
                                            ];
                                            $calcStatusColor = $calcStatusColors[$entry->calculation_status] ?? 'bg-gray-100 text-gray-800';
                                        @endphp
                                        <span class="quickbooks-badge {{ $calcStatusColor }}">
                                            {{ ucfirst($entry->calculation_status) }}
                                        </span>
                                    </td>
                                    <td>
                                        @php
                                            $paymentStatusColors = [
                                                'pending' => 'bg-yellow-100 text-yellow-800',
                                                'paid' => 'bg-green-100 text-green-800',
                                                'failed' => 'bg-red-100 text-red-800'
                                            ];
                                            $paymentStatusColor = $paymentStatusColors[$entry->payment_status] ?? 'bg-gray-100 text-gray-800';
                                        @endphp
                                        <span class="quickbooks-badge {{ $paymentStatusColor }}">
                                            {{ ucfirst($entry->payment_status) }}
                                        </span>
                                    </td>
                                    <td class="font-medium text-gray900">
                                        {{ $company->currency_symbol ?? 'K' }}{{ number_format($entry->gross_earnings, 2) }}
                                    </td>
                                    <td class="font-medium text-danger">
                                        {{ $company->currency_symbol ?? 'K' }}{{ number_format($entry->total_deductions, 2) }}
                                    </td>
                                    <td class="font-medium text-success">
                                        {{ $company->currency_symbol ?? 'K' }}{{ number_format($entry->net_pay, 2) }}
                                    </td>
                                    <td>
                                        <div class="flex items-center">
                                            <!-- View Entry Details -->
                                            <button onclick="viewEntryDetails({{ $entry->id }})" 
                                                   class="action-btn action-btn-view"
                                                   title="View details">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            
                                            <!-- Approve Button (only if calculated) -->
                                            @if($entry->calculation_status === 'calculated')
                                                <button onclick="approveEntry({{ $entry->id }})" 
                                                        class="action-btn action-btn-approve"
                                                        title="Approve Entry">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                            @endif
                                            
                                            <!-- Mark as Paid Button (only if approved and pending payment) -->
                                            @if($entry->calculation_status === 'approved' && $entry->payment_status === 'pending')
                                                <button onclick="processEntryPayment({{ $entry->id }})" 
                                                        class="action-btn action-btn-pay"
                                                        title="Mark as Paid">
                                                    <i class="fas fa-money-check"></i>
                                                </button>
                                            @endif
                                            
                                            <!-- Export Button (only if approved or paid) -->
                                            @if(in_array($entry->calculation_status, ['approved', 'paid']))
                                                <button onclick="exportEntry({{ $entry->id }})" 
                                                        class="action-btn action-btn-export"
                                                        title="Export">
                                                    <i class="fas fa-download"></i>
                                                </button>
                                            @endif
                                            
                                            <!-- Payroll Run Actions (if run exists) -->
                                            @if($run && $run->status === 'calculated')
                                                <a href="{{ route('admin.accounting.payroll.processing.review', $run->id) }}" 
                                                   class="action-btn action-btn-approve ml-1"
                                                   title="Review & Approve Run">
                                                    <i class="fas fa-list-check"></i>
                                                </a>
                                            @endif
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="9" class="text-center py-8">
                                        <div id="emptyState" class="py-16 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-calculator text-gray500 text-2xl"></i>
                                            </div>
                                            <h3 class="text-lg font-medium text-gray900 mb-2">No payroll entries found</h3>
                                            <p class="text-gray600 mb-6 max-w-md mx-auto">
                                                @if($status == 'calculated')
                                                    No calculated entries pending review.
                                                @elseif($status == 'approved')
                                                    No approved entries pending payment.
                                                @elseif($status == 'paid')
                                                    No paid entries found in the last 30 days.
                                                @else
                                                    Start by processing payroll for an open period.
                                                @endif
                                            </p>
                                            <div class="space-x-3">
                                                <button onclick="processNewPayroll()" 
                                                        class="bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90">
                                                    <i class="fas fa-plus mr-2"></i>Process Payroll
                                                </button>
                                                <a href="{{ route('admin.accounting.payroll.periods.index') }}" 
                                                   class="border border-gray300 text-gray700 px-4 py-2 rounded text-sm font-medium hover:bg-gray50">
                                                    <i class="fas fa-calendar-alt mr-2"></i>View Periods
                                                </a>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                @if($payrollEntries->hasPages())
                    <div class="border-t border-gray200 p-4 flex items-center justify-between">
                        <div class="text-sm text-gray600">
                            Showing {{ $payrollEntries->firstItem() }} to {{ $payrollEntries->lastItem() }} of {{ $payrollEntries->total() }} entries
                        </div>
                        <div class="flex items-center space-x-1">
                            {{ $payrollEntries->appends(request()->query())->links('vendor.pagination.tailwind') }}
                        </div>
                    </div>
                @endif
            </div>
        </main>
    </div>

    <!-- Process New 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="p-6">
                <div class="flex items-center mb-4">
                    <div class="w-10 h-10 bg-primaryLight rounded-lg flex items-center justify-center mr-3">
                        <i class="fas fa-calculator text-primary"></i>
                    </div>
                    <div>
                        <h3 class="text-lg font-semibold text-gray900">Process New Payroll</h3>
                        <p class="text-gray600 text-sm">Select a payroll period to process</p>
                    </div>
                </div>
                
                <div class="space-y-4">
                    <div>
                        <label class="text-sm font-medium text-gray700 block mb-2">Select Period</label>
                        <select id="periodSelect" class="quickbooks-input w-full">
                            <option value="">Select a period</option>
                            @php
                                $openPeriods = \App\Models\PayrollPeriod::where('company_id', $company->id)
                                    ->where('status', 'open')
                                    ->where('is_active', true)
                                    ->orderBy('start_date', 'desc')
                                    ->get();
                            @endphp
                            @foreach($openPeriods as $period)
                                <option value="{{ $period->id }}">
                                    {{ $period->period_name }} ({{ $period->start_date->format('M d') }} - {{ $period->end_date->format('M d, Y') }})
                                </option>
                            @endforeach
                        </select>
                    </div>
                    
                    @if($openPeriods->isEmpty())
                        <div class="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>
                                <div>
                                    <p class="text-sm text-yellow-800 font-medium">No open periods available</p>
                                    <p class="text-xs text-yellow-600 mt-1">Create or open a payroll period first.</p>
                                </div>
                            </div>
                        </div>
                    @endif
                </div>
            </div>
            
            <div class="border-t border-gray200 p-6 flex justify-end space-x-3">
                <button onclick="closeProcessModal()" class="px-4 py-2 text-gray700 hover:bg-gray100 rounded text-sm font-medium">
                    Cancel
                </button>
                <button onclick="startPayrollProcessing()" 
                        class="bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90"
                        {{ $openPeriods->isEmpty() ? 'disabled' : '' }}>
                    Continue
                </button>
            </div>
        </div>
    </div>

    <!-- Entry Details Modal -->
    <div id="entryDetailsModal" 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-2xl w-full max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <div class="flex items-center">
                        <div class="w-10 h-10 bg-primaryLight rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-file-invoice-dollar text-primary"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-semibold text-gray900" id="entryDetailsTitle">Payroll Entry Details</h3>
                            <p class="text-gray600 text-sm" id="entryDetailsSubtitle"></p>
                        </div>
                    </div>
                    <button onclick="closeEntryDetailsModal()" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div id="entryDetailsContent" class="space-y-4">
                    <!-- Content will be loaded via AJAX -->
                </div>
            </div>
        </div>
    </div>

    <!-- Payment Processing Modal for Single Entry -->
    <div id="paymentEntryModal" 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="p-6">
                <div class="flex items-center mb-4">
                    <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center mr-3">
                        <i class="fas fa-money-check-alt text-success"></i>
                    </div>
                    <div>
                        <h3 class="text-lg font-semibold text-gray900" id="paymentEntryModalTitle">Mark Entry as Paid</h3>
                        <p class="text-gray600 text-sm" id="paymentEntryModalMessage"></p>
                    </div>
                </div>
                
                <form id="paymentEntryForm">
                    @csrf
                    <div class="space-y-4">
                        <div>
                            <label class="text-sm font-medium text-gray700 block mb-2">Payment Date</label>
                            <input type="date" 
                                   id="entry_payment_date"
                                   name="payment_date" 
                                   class="quickbooks-input w-full"
                                   value="{{ date('Y-m-d') }}">
                        </div>
                        <div>
                            <label class="text-sm font-medium text-gray700 block mb-2">Payment Reference</label>
                            <input type="text" 
                                   id="entry_payment_reference"
                                   name="payment_reference" 
                                   class="quickbooks-input w-full"
                                   placeholder="e.g., BANK-TRANS-001">
                        </div>
                    </div>
                </form>
            </div>
            
            <div class="border-t border-gray200 p-6 flex justify-end space-x-3">
                <button onclick="closePaymentEntryModal()" class="px-4 py-2 text-gray700 hover:bg-gray100 rounded text-sm font-medium">
                    Cancel
                </button>
                <button onclick="confirmEntryPayment()" class="bg-success text-white px-4 py-2 rounded text-sm font-medium hover:bg-success/90">
                    Mark as Paid
                </button>
            </div>
        </div>
    </div>

    <script>
        let currentEntryId = null;
        let currentPaymentEntryId = null;

        // Helper function to get base URL
        function getBaseUrl() {
            return window.location.origin + '/finerp/public';
        }

        // Filter by status
        function filterByStatus(status) {
            const url = new URL(window.location.href);
            url.searchParams.set('status', status);
            window.location.href = url.toString();
        }

        // Process new payroll
        function processNewPayroll() {
            document.getElementById('processPayrollModal').classList.remove('hidden');
        }

        function closeProcessModal() {
            document.getElementById('processPayrollModal').classList.add('hidden');
        }

        function startPayrollProcessing() {
            const periodId = document.getElementById('periodSelect').value;
            if (!periodId) {
                showNotification('Please select a payroll period', 'error');
                return;
            }
            
            window.location.href = getBaseUrl() + '/admin/accounting/payroll/processing/create/' + periodId;
        }

        // View entry details
        function viewEntryDetails(entryId) {
            currentEntryId = entryId;
            
            // Show loading
            document.getElementById('entryDetailsContent').innerHTML = `
                <div class="text-center py-8">
                    <i class="fas fa-spinner fa-spin text-primary text-2xl mb-2"></i>
                    <p class="text-gray600">Loading details...</p>
                </div>
            `;
            
            document.getElementById('entryDetailsModal').classList.remove('hidden');
            
            // Load entry details via AJAX
            fetch(getBaseUrl() + '/admin/accounting/payroll/processing/entry/' + entryId + '/details', {
                method: 'GET',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '{{ csrf_token() }}',
                    'Accept': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('entryDetailsTitle').textContent = `Payroll Entry: ${data.employee_name}`;
                    document.getElementById('entryDetailsSubtitle').textContent = 
                        `Period: ${data.period_name} | Entry Date: ${data.entry_date}`;
                    document.getElementById('entryDetailsContent').innerHTML = data.html;
                } else {
                    document.getElementById('entryDetailsContent').innerHTML = `
                        <div class="text-center py-8">
                            <i class="fas fa-exclamation-triangle text-yellow-500 text-2xl mb-2"></i>
                            <p class="text-gray600">Failed to load entry details</p>
                            <p class="text-sm text-gray500">${data.message}</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                document.getElementById('entryDetailsContent').innerHTML = `
                    <div class="text-center py-8">
                        <i class="fas fa-exclamation-triangle text-red-500 text-2xl mb-2"></i>
                        <p class="text-gray600">Failed to load entry details</p>
                        <p class="text-sm text-gray500">Network error occurred</p>
                    </div>
                `;
            });
        }

        function closeEntryDetailsModal() {
            document.getElementById('entryDetailsModal').classList.add('hidden');
            currentEntryId = null;
        }

        // Approve entry
        function approveEntry(entryId) {
            if (!confirm('Are you sure you want to approve this payroll entry?')) {
                return;
            }
            
            fetch(getBaseUrl() + '/admin/accounting/payroll/processing/entry/' + entryId + '/approve', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '{{ csrf_token() }}',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({})
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Failed to approve entry: ' + error.message, 'error');
            });
        }

        // Payment processing for single entry
        function processEntryPayment(entryId) {
            currentPaymentEntryId = entryId;
            
            // Get entry details
            const entryRow = document.querySelector(`tr:has(button[onclick="processEntryPayment(${entryId})"])`);
            const employeeName = entryRow?.querySelector('td:first-child .font-medium')?.textContent || 'Employee';
            const netPay = entryRow?.querySelector('td:nth-child(8)')?.textContent || '0.00';
            
            document.getElementById('paymentEntryModalTitle').textContent = 'Mark Entry as Paid';
            document.getElementById('paymentEntryModalMessage').textContent = 
                `Confirm payment for ${employeeName}. Net Pay: ${netPay}`;
            
            document.getElementById('paymentEntryModal').classList.remove('hidden');
        }

        function closePaymentEntryModal() {
            document.getElementById('paymentEntryModal').classList.add('hidden');
            currentPaymentEntryId = null;
        }

        function confirmEntryPayment() {
            if (!currentPaymentEntryId) return;
            
            const formData = new FormData(document.getElementById('paymentEntryForm'));
            
            fetch(getBaseUrl() + '/admin/accounting/payroll/processing/entry/' + currentPaymentEntryId + '/pay', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '{{ csrf_token() }}',
                    'Accept': 'application/json',
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showNotification(data.message, 'error');
                }
                closePaymentEntryModal();
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Failed to process payment: ' + error.message, 'error');
                closePaymentEntryModal();
            });
        }

        // Export entry
        function exportEntry(entryId) {
            const exportType = confirm('Export as:\n\nClick OK for PDF Payslip\nClick Cancel for CSV');
            
            if (exportType) {
                // Export to PDF
                window.open(getBaseUrl() + '/admin/accounting/payroll/reports/employee-payslip/' + entryId, '_blank');
            } else {
                // Export to CSV
                window.open(getBaseUrl() + '/admin/accounting/payroll/processing/entry/' + entryId + '/export', '_blank');
            }
        }

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

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

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

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

            document.body.appendChild(notification);

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

        // Add animation styles
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(-10px); }
                to { opacity: 1; transform: translateY(0); }
            }
            @keyframes fadeOut {
                from { opacity: 1; transform: translateY(0); }
                to { opacity: 0; transform: translateY(-10px); }
            }
            .animate-fade-in {
                animation: fadeIn 0.3s ease-out;
            }
            .animate-fade-out {
                animation: fadeOut 0.3s ease-in;
            }
            .quickbooks-input {
                border: 1px solid #E1DFDD;
                border-radius: 4px;
                padding: 8px 12px;
                font-size: 14px;
                transition: border-color 0.2s;
            }
            .quickbooks-input:focus {
                outline: none;
                border-color: #146CAA;
                box-shadow: 0 0 0 2px rgba(20, 108, 170, 0.1);
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>