<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leave Balances</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-input {
            border: 1px solid #E1DFDD;
            border-radius: 4px;
            padding: 8px 12px;
            font-size: 14px;
            transition: border-color 0.2s;
            width: 100%;
        }
        .quickbooks-input:focus {
            outline: none;
            border-color: #146CAA;
            box-shadow: 0 0 0 2px rgba(20, 108, 170, 0.1);
        }
        
        .balance-badge {
            display: inline-flex;
            align-items: center;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-high {
            background-color: #E1F0FA;
            color: #107C10;
        }
        
        .badge-medium {
            background-color: #FEF7E0;
            color: #F68C1E;
        }
        
        .badge-low {
            background-color: #FEE8E6;
            color: #D83B01;
        }
        
        .badge-zero {
            background-color: #F3F2F1;
            color: #605E5C;
        }
        
        .progress-bar {
            height: 8px;
            background-color: #E1DFDD;
            border-radius: 4px;
            overflow: hidden;
            margin-top: 4px;
        }
        
        .progress-fill {
            height: 100%;
            border-radius: 4px;
            transition: width 0.3s ease;
        }
        
        .progress-high {
            background-color: #107C10;
        }
        
        .progress-medium {
            background-color: #F68C1E;
        }
        
        .progress-low {
            background-color: #D83B01;
        }
        
        .modal-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .modal-overlay.active {
            display: flex !important;
        }
        
        .modal-content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 500px;
            margin: 1rem;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
            z-index: 1001;
            transform: translateZ(0);
            animation: modalSlideIn 0.3s ease-out;
        }
    </style>
</head>
<body class="bg-gray50">
    @include('accounting.partials.sidebar')

    <div class="lg:ml-64">
        <!-- Header -->
        <header class="bg-white border-b border-gray200 py-4 px-6">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-xl font-bold text-gray900">Leave Balances</h1>
                    <nav class="flex space-x-2 text-sm text-gray600 mt-1">
                        <a href="{{ route('admin.accounting.index') }}" class="hover:text-primary">Dashboard</a>
                        <span>/</span>
                        <a href="{{ route('admin.accounting.payroll.index') }}" class="hover:text-primary">Payroll</a>
                        <span>/</span>
                        <a href="{{ route('admin.accounting.payroll.leave.index') }}" class="hover:text-primary">Leave Management</a>
                        <span>/</span>
                        <span class="text-gray900">Leave Balances</span>
                    </nav>
                </div>
                <div class="flex items-center space-x-3">
                    <button onclick="openAdjustModal()" 
                            class="flex items-center space-x-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary/90">
                        <i class="fas fa-plus"></i>
                        <span>Adjust Balance</span>
                    </button>
                    <button onclick="openAccrualModal()" 
                            class="flex items-center space-x-2 px-4 py-2 bg-success text-white rounded-lg text-sm font-medium hover:bg-success/90">
                        <i class="fas fa-calculator"></i>
                        <span>Process Accrual</span>
                    </button>
                </div>
            </div>
        </header>

        <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 animate-fade-in">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <i class="fas fa-check-circle text-green-500 mr-2"></i>
                            <span class="text-green-800 font-medium">{{ session('success') }}</span>
                        </div>
                        <button onclick="this.parentElement.parentElement.remove()" class="text-green-600 hover:text-green-800">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            @endif

            @if(session('error'))
                <div class="mb-6 bg-red-50 border border-red-200 rounded-lg p-4 animate-fade-in">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                            <span class="text-red-800 font-medium">{{ session('error') }}</span>
                        </div>
                        <button onclick="this.parentElement.parentElement.remove()" class="text-red-600 hover:text-red-800">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            @endif

            <!-- Summary Statistics -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                @foreach($leaveTypes as $type)
                <div class="bg-white rounded-lg border border-gray200 p-6 hover:shadow-md">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray600 text-sm font-medium mb-1">{{ $type->name }}</p>
                            <h3 class="text-2xl font-bold text-gray900">
                                {{ number_format($totalBalances[$type->id] ?? 0, 1) }}
                            </h3>
                        </div>
                        <div class="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                            <i class="fas fa-umbrella-beach text-blue-600"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <div class="text-xs text-gray500">Total Days Available</div>
                        @if($type->max_days_per_year)
                        @php
                            $percentage = $employees->count() > 0 ? 
                                (($totalBalances[$type->id] ?? 0) / ($type->max_days_per_year * $employees->count())) * 100 : 0;
                            $percentage = min(100, $percentage);
                        @endphp
                        <div class="progress-bar">
                            <div class="progress-fill {{ $percentage > 66 ? 'progress-high' : ($percentage > 33 ? 'progress-medium' : 'progress-low') }}" 
                                 style="width: {{ $percentage }}%"></div>
                        </div>
                        @endif
                    </div>
                </div>
                @endforeach
            </div>

            <!-- Leave Balances 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>
                                @foreach($leaveTypes as $type)
                                <th>{{ $type->name }}</th>
                                @endforeach
                                <th>Total Balance</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($employees as $employee)
                            <tr class="hover:bg-gray100">
                                <td>
                                    <div class="flex items-center space-x-3">
                                        <div class="w-8 h-8 rounded-full bg-primaryLight flex items-center justify-center">
                                            <span class="text-primary text-sm font-medium">
                                                {{ substr($employee->first_name, 0, 1) }}{{ substr($employee->last_name, 0, 1) }}
                                            </span>
                                        </div>
                                        <div>
                                            <div class="font-medium text-gray900">{{ $employee->full_name }}</div>
                                            <div class="text-xs text-gray500">{{ $employee->employee_number }}</div>
                                        </div>
                                    </div>
                                </td>
                                
                                @foreach($leaveTypes as $type)
                                @php
                                    $balance = $employee->leaveBalances->firstWhere('leave_type_id', $type->id);
                                    $availableBalance = $balance ? $balance->available_balance : 0;
                                    $totalAccrued = $balance ? $balance->total_accrued : 0;
                                    $totalTaken = $balance ? $balance->total_taken : 0;
                                    
                                    // Determine badge class
                                    $badgeClass = 'badge-zero';
                                    if ($availableBalance > 10) {
                                        $badgeClass = 'badge-high';
                                    } elseif ($availableBalance > 5) {
                                        $badgeClass = 'badge-medium';
                                    } elseif ($availableBalance > 0) {
                                        $badgeClass = 'badge-low';
                                    }
                                    
                                    // Calculate percentage for progress bar
                                    $percentage = $type->max_days_per_year ? 
                                        min(100, ($availableBalance / $type->max_days_per_year) * 100) : 
                                        ($availableBalance > 0 ? 100 : 0);
                                @endphp
                                <td>
                                    <div class="text-sm font-medium text-gray900">{{ number_format($availableBalance, 1) }}</div>
                                    <div class="text-xs text-gray500">
                                        Accrued: {{ number_format($totalAccrued, 1) }} | 
                                        Taken: {{ number_format($totalTaken, 1) }}
                                    </div>
                                    @if($percentage > 0)
                                    <div class="progress-bar">
                                        <div class="progress-fill {{ $percentage > 66 ? 'progress-high' : ($percentage > 33 ? 'progress-medium' : 'progress-low') }}" 
                                             style="width: {{ $percentage }}%"></div>
                                    </div>
                                    @endif
                                </td>
                                @endforeach
                                
                                @php
                                    $totalEmployeeBalance = $employee->leaveBalances->sum('available_balance');
                                    $totalBadgeClass = 'badge-zero';
                                    if ($totalEmployeeBalance > 30) {
                                        $totalBadgeClass = 'badge-high';
                                    } elseif ($totalEmployeeBalance > 15) {
                                        $totalBadgeClass = 'badge-medium';
                                    } elseif ($totalEmployeeBalance > 0) {
                                        $totalBadgeClass = 'badge-low';
                                    }
                                @endphp
                                <td>
                                    <span class="balance-badge {{ $totalBadgeClass }}">
                                        {{ number_format($totalEmployeeBalance, 1) }} days
                                    </span>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="{{ count($leaveTypes) + 2 }}" class="text-center py-12">
                                    <div class="text-center text-gray500">
                                        <i class="fas fa-users text-4xl mb-3"></i>
                                        <p>No employees found</p>
                                    </div>
                                </td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                @if($employees->hasPages())
                <div class="p-6 border-t border-gray200">
                    <div class="flex items-center justify-between">
                        <div class="text-sm text-gray600">
                            Showing {{ $employees->firstItem() }} to {{ $employees->lastItem() }} of {{ $employees->total() }} entries
                        </div>
                        <div class="flex space-x-2">
                            @if($employees->onFirstPage())
                            <span class="px-3 py-1 rounded bg-gray100 text-gray500 text-sm">Previous</span>
                            @else
                            <a href="{{ $employees->previousPageUrl() }}" class="px-3 py-1 rounded bg-gray100 hover:bg-gray200 text-gray700 text-sm">Previous</a>
                            @endif
                            
                            @foreach($employees->getUrlRange(1, $employees->lastPage()) as $page => $url)
                                @if($page == $employees->currentPage())
                                <span class="px-3 py-1 rounded bg-primary text-white text-sm">{{ $page }}</span>
                                @else
                                <a href="{{ $url }}" class="px-3 py-1 rounded bg-gray100 hover:bg-gray200 text-gray700 text-sm">{{ $page }}</a>
                                @endif
                            @endforeach
                            
                            @if($employees->hasMorePages())
                            <a href="{{ $employees->nextPageUrl() }}" class="px-3 py-1 rounded bg-gray100 hover:bg-gray200 text-gray700 text-sm">Next</a>
                            @else
                            <span class="px-3 py-1 rounded bg-gray100 text-gray500 text-sm">Next</span>
                            @endif
                        </div>
                    </div>
                </div>
                @endif
            </div>
        </main>
    </div>

    <!-- Adjust Balance Modal -->
    <div id="adjustModal" class="modal-overlay">
        <div class="modal-content">
            <div class="flex items-center justify-between p-6 border-b border-gray200">
                <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-plus text-primary"></i>
                    </div>
                    <div>
                        <h3 class="text-lg font-semibold text-gray900">Adjust Leave Balance</h3>
                        <p class="text-gray600 text-sm mt-1">Manually adjust an employee's leave balance</p>
                    </div>
                </div>
                <button onclick="closeAdjustModal()" class="text-gray500 hover:text-gray700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="p-6">
                <form id="adjustForm" method="POST" action="{{ route('admin.accounting.payroll.leave.balances.adjust') }}">
                    @csrf
                    <div class="space-y-4">
                        <!-- Employee -->
                        <div>
                            <label for="adjust_employee_id" class="block text-sm font-medium text-gray700 mb-2 required">Employee *</label>
                            <select name="employee_id" 
                                    id="adjust_employee_id"
                                    class="quickbooks-input"
                                    required
                                    onchange="loadEmployeeBalance()">
                                <option value="">Select Employee</option>
                                @foreach($employees as $employee)
                                <option value="{{ $employee->id }}">
                                    {{ $employee->full_name }} ({{ $employee->employee_number }})
                                </option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Leave Type -->
                        <div>
                            <label for="adjust_leave_type_id" class="block text-sm font-medium text-gray700 mb-2 required">Leave Type *</label>
                            <select name="leave_type_id" 
                                    id="adjust_leave_type_id"
                                    class="quickbooks-input"
                                    required
                                    onchange="loadEmployeeBalance()">
                                <option value="">Select Leave Type</option>
                                @foreach($leaveTypes as $type)
                                <option value="{{ $type->id }}">{{ $type->name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Current Balance Display -->
                        <div id="currentBalance" class="balance-info bg-gray100 p-4 rounded-lg hidden">
                            <div class="text-center">
                                <div class="text-sm text-gray600 mb-1">Current Balance</div>
                                <div class="text-2xl font-bold text-primary" id="balanceValue">0.00 days</div>
                                <div class="text-xs text-gray500 mt-2" id="balanceDetails"></div>
                            </div>
                        </div>

                        <!-- Adjustment Type -->
                        <div>
                            <label class="block text-sm font-medium text-gray700 mb-2 required">Adjustment Type *</label>
                            <div class="space-y-2">
                                <label class="flex items-center">
                                    <input type="radio" 
                                           name="adjustment_type" 
                                           value="add_accrual"
                                           class="mr-2"
                                           checked>
                                    <span class="text-sm text-gray700">Add Accrual</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="radio" 
                                           name="adjustment_type" 
                                           value="add_taken"
                                           class="mr-2">
                                    <span class="text-sm text-gray700">Add Taken Days</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="radio" 
                                           name="adjustment_type" 
                                           value="adjust_balance"
                                           class="mr-2">
                                    <span class="text-sm text-gray700">Adjust Balance Directly</span>
                                </label>
                            </div>
                        </div>

                        <!-- Days -->
                        <div>
                            <label for="adjust_days" class="block text-sm font-medium text-gray700 mb-2 required">Days *</label>
                            <input type="number" 
                                   name="days" 
                                   id="adjust_days"
                                   class="quickbooks-input"
                                   placeholder="Enter number of days"
                                   step="0.01"
                                   min="0.01"
                                   required>
                        </div>

                        <!-- Notes -->
                        <div>
                            <label for="adjust_notes" class="block text-sm font-medium text-gray700 mb-2">Notes</label>
                            <textarea name="notes" 
                                      id="adjust_notes"
                                      rows="2"
                                      class="quickbooks-input resize-none"
                                      placeholder="Optional notes about this adjustment"></textarea>
                        </div>
                    </div>

                    <div class="flex justify-end gap-3 mt-6 pt-6 border-t border-gray200">
                        <button type="button" 
                                onclick="closeAdjustModal()" 
                                class="px-4 py-2 text-gray700 hover:bg-gray100 rounded text-sm font-medium">
                            Cancel
                        </button>
                        <button type="submit" 
                                id="adjustSubmitBtn"
                                class="bg-primary text-white px-4 py-2 rounded text-sm font-medium hover:bg-primary/90 flex items-center gap-2">
                            <i class="fas fa-check"></i>
                            Apply Adjustment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Process Accrual Modal -->
    <div id="accrualModal" class="modal-overlay">
        <div class="modal-content">
            <div class="flex items-center justify-between p-6 border-b border-gray200">
                <div class="flex items-center">
                    <div class="w-10 h-10 bg-successLight rounded-lg flex items-center justify-center mr-3">
                        <i class="fas fa-calculator text-success"></i>
                    </div>
                    <div>
                        <h3 class="text-lg font-semibold text-gray900">Process Leave Accrual</h3>
                        <p class="text-gray600 text-sm mt-1">Process monthly leave accrual for employees</p>
                    </div>
                </div>
                <button onclick="closeAccrualModal()" class="text-gray500 hover:text-gray700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="p-6">
                <form id="accrualForm" method="POST" action="{{ route('admin.accounting.payroll.leave.balances.process-accrual') }}">
                    @csrf
                    <div class="space-y-4">
                        <!-- Leave Type -->
                        <div>
                            <label for="accrual_leave_type_id" class="block text-sm font-medium text-gray700 mb-2 required">Leave Type *</label>
                            <select name="leave_type_id" 
                                    id="accrual_leave_type_id"
                                    class="quickbooks-input"
                                    required
                                    onchange="updateAccrualInfo()">
                                <option value="">Select Leave Type</option>
                                @foreach($leaveTypes as $type)
                                <option value="{{ $type->id }}" data-rate="{{ $type->accrual_rate_days }}">
                                    {{ $type->name }} 
                                    @if($type->accrual_rate_days)
                                    ({{ $type->accrual_rate_days }} days/month)
                                    @endif
                                </option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Accrual Date -->
                        <div>
                            <label for="accrual_date" class="block text-sm font-medium text-gray700 mb-2 required">Accrual Date *</label>
                            <input type="date" 
                                   name="accrual_date" 
                                   id="accrual_date"
                                   class="quickbooks-input"
                                   value="{{ date('Y-m-d') }}"
                                   required>
                        </div>

                        <!-- Accrual Rate Info -->
                        <div id="accrualInfo" class="bg-blue-50 border border-blue-200 rounded-lg p-4 hidden">
                            <div class="text-sm text-blue-800">
                                <i class="fas fa-info-circle mr-2"></i>
                                <span id="accrualRateText">Accrual rate: 0 days/month</span>
                            </div>
                        </div>

                        <!-- Employees Selection -->
                        <div>
                            <label class="block text-sm font-medium text-gray700 mb-2">Employees *</label>
                            <div class="space-y-2">
                                <label class="flex items-center">
                                    <input type="radio" 
                                           name="accrue_for_all" 
                                           value="1"
                                           class="mr-2"
                                           checked
                                           onchange="toggleEmployeeSelection()">
                                    <span class="text-sm text-gray700">All Active Employees</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="radio" 
                                           name="accrue_for_all" 
                                           value="0"
                                           class="mr-2"
                                           onchange="toggleEmployeeSelection()">
                                    <span class="text-sm text-gray700">Select Specific Employees</span>
                                </label>
                            </div>
                        </div>

                        <!-- Employee Selection (hidden by default) -->
                        <div id="employeeSelection" class="hidden">
                            <label class="block text-sm font-medium text-gray700 mb-2">Select Employees</label>
                            <div class="max-h-48 overflow-y-auto border border-gray300 rounded-lg p-3">
                                @foreach($employees as $employee)
                                <label class="flex items-center mb-2">
                                    <input type="checkbox" 
                                           name="employee_ids[]" 
                                           value="{{ $employee->id }}"
                                           class="mr-2">
                                    <span class="text-sm text-gray700">
                                        {{ $employee->full_name }} ({{ $employee->employee_number }})
                                    </span>
                                </label>
                                @endforeach
                            </div>
                        </div>

                        <!-- Estimated Impact -->
                        <div id="estimatedImpact" class="bg-green-50 border border-green-200 rounded-lg p-4 hidden">
                            <div class="text-sm text-green-800">
                                <i class="fas fa-chart-line mr-2"></i>
                                <span id="impactText">Estimated impact: 0 days will be accrued</span>
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-end gap-3 mt-6 pt-6 border-t border-gray200">
                        <button type="button" 
                                onclick="closeAccrualModal()" 
                                class="px-4 py-2 text-gray700 hover:bg-gray100 rounded text-sm font-medium">
                            Cancel
                        </button>
                        <button type="submit" 
                                id="accrualSubmitBtn"
                                class="bg-success text-white px-4 py-2 rounded text-sm font-medium hover:bg-success/90 flex items-center gap-2">
                            <i class="fas fa-calculator"></i>
                            Process Accrual
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Base URL configuration
        const BASE_URL = '{{ url('/') }}';

        // Modal Functions
        function openAdjustModal() {
            const modal = document.getElementById('adjustModal');
            modal.classList.add('active');
            document.body.classList.add('no-scroll');
            
            setTimeout(() => {
                const employeeSelect = document.getElementById('adjust_employee_id');
                if (employeeSelect) employeeSelect.focus();
            }, 100);
        }

        function closeAdjustModal() {
            const modal = document.getElementById('adjustModal');
            modal.classList.remove('active');
            document.body.classList.remove('no-scroll');
            const adjustForm = document.getElementById('adjustForm');
            if (adjustForm) adjustForm.reset();
            document.getElementById('currentBalance').classList.add('hidden');
        }

        function openAccrualModal() {
            const modal = document.getElementById('accrualModal');
            modal.classList.add('active');
            document.body.classList.add('no-scroll');
            
            setTimeout(() => {
                const leaveTypeSelect = document.getElementById('accrual_leave_type_id');
                if (leaveTypeSelect) leaveTypeSelect.focus();
            }, 100);
        }

        function closeAccrualModal() {
            const modal = document.getElementById('accrualModal');
            modal.classList.remove('active');
            document.body.classList.remove('no-scroll');
            const accrualForm = document.getElementById('accrualForm');
            if (accrualForm) accrualForm.reset();
            document.getElementById('accrualInfo').classList.add('hidden');
            document.getElementById('estimatedImpact').classList.add('hidden');
            document.getElementById('employeeSelection').classList.add('hidden');
        }

        // Close modals with Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeAdjustModal();
                closeAccrualModal();
            }
        });

        // Load employee balance for adjustment
        async function loadEmployeeBalance() {
            const employeeId = document.getElementById('adjust_employee_id').value;
            const leaveTypeId = document.getElementById('adjust_leave_type_id').value;
            const balanceDiv = document.getElementById('currentBalance');
            
            if (!employeeId || !leaveTypeId) {
                balanceDiv.classList.add('hidden');
                return;
            }
            
            try {
                const response = await fetch(`${BASE_URL}/admin/accounting/payroll/leave/balance/${employeeId}/${leaveTypeId}`);
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('balanceValue').textContent = data.balance + ' days';
                    
                    const details = [
                        `Accrued: ${data.total_accrued} days`,
                        `Taken: ${data.total_taken} days`
                    ];
                    
                    if (data.carry_forward_balance) {
                        details.push(`Carry Forward: ${data.carry_forward_balance} days`);
                    }
                    
                    document.getElementById('balanceDetails').textContent = details.join(' • ');
                    balanceDiv.classList.remove('hidden');
                }
            } catch (error) {
                console.error('Error loading balance:', error);
                balanceDiv.classList.add('hidden');
            }
        }

        // Toggle employee selection for accrual
        function toggleEmployeeSelection() {
            const accrueForAll = document.querySelector('input[name="accrue_for_all"]:checked').value;
            const employeeSelection = document.getElementById('employeeSelection');
            
            if (accrueForAll === '0') {
                employeeSelection.classList.remove('hidden');
            } else {
                employeeSelection.classList.add('hidden');
            }
            
            updateAccrualInfo();
        }

        // Update accrual information
        function updateAccrualInfo() {
            const leaveTypeSelect = document.getElementById('accrual_leave_type_id');
            const selectedOption = leaveTypeSelect.options[leaveTypeSelect.selectedIndex];
            const accrualRate = selectedOption ? selectedOption.getAttribute('data-rate') : 0;
            const accrualInfo = document.getElementById('accrualInfo');
            const estimatedImpact = document.getElementById('estimatedImpact');
            
            if (accrualRate && parseFloat(accrualRate) > 0) {
                document.getElementById('accrualRateText').textContent = 
                    `Accrual rate: ${accrualRate} days/month`;
                accrualInfo.classList.remove('hidden');
                
                // Calculate estimated impact
                const accrueForAll = document.querySelector('input[name="accrue_for_all"]:checked').value;
                let employeeCount = {{ $employees->count() }};
                
                if (accrueForAll === '0') {
                    // Count selected employees
                    const selectedEmployees = document.querySelectorAll('input[name="employee_ids[]"]:checked').length;
                    employeeCount = selectedEmployees;
                }
                
                const totalDays = parseFloat(accrualRate) * employeeCount;
                document.getElementById('impactText').textContent = 
                    `Estimated impact: ${totalDays.toFixed(2)} days will be accrued for ${employeeCount} employee(s)`;
                estimatedImpact.classList.remove('hidden');
            } else {
                accrualInfo.classList.add('hidden');
                estimatedImpact.classList.add('hidden');
            }
        }

        // Form submission handlers
        const adjustForm = document.getElementById('adjustForm');
        if (adjustForm) {
            adjustForm.addEventListener('submit', function(e) {
                const submitBtn = document.getElementById('adjustSubmitBtn');
                const employeeId = document.getElementById('adjust_employee_id').value;
                const leaveTypeId = document.getElementById('adjust_leave_type_id').value;
                const days = document.getElementById('adjust_days').value;
                
                if (!employeeId || !leaveTypeId || !days) {
                    e.preventDefault();
                    alert('Please fill in all required fields.');
                    return false;
                }
                
                if (parseFloat(days) <= 0) {
                    e.preventDefault();
                    alert('Days must be greater than 0.');
                    return false;
                }
                
                if (submitBtn) {
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Processing...';
                }
            });
        }

        const accrualForm = document.getElementById('accrualForm');
        if (accrualForm) {
            accrualForm.addEventListener('submit', function(e) {
                const submitBtn = document.getElementById('accrualSubmitBtn');
                const leaveTypeId = document.getElementById('accrual_leave_type_id').value;
                const accrueForAll = document.querySelector('input[name="accrue_for_all"]:checked').value;
                
                if (!leaveTypeId) {
                    e.preventDefault();
                    alert('Please select a leave type.');
                    return false;
                }
                
                if (accrueForAll === '0') {
                    const selectedEmployees = document.querySelectorAll('input[name="employee_ids[]"]:checked').length;
                    if (selectedEmployees === 0) {
                        e.preventDefault();
                        alert('Please select at least one employee.');
                        return false;
                    }
                }
                
                if (submitBtn) {
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Processing...';
                }
            });
        }

        // Auto-hide alerts after 5 seconds
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                const alerts = document.querySelectorAll('.bg-green-50, .bg-red-50');
                alerts.forEach(alert => {
                    if (alert) {
                        alert.style.opacity = '0';
                        alert.style.transition = 'opacity 0.5s ease';
                        setTimeout(() => {
                            if (alert.parentNode) {
                                alert.parentNode.removeChild(alert);
                            }
                        }, 500);
                    }
                });
            }, 5000);
            
            // Add event listeners for accrual form
            const accrualLeaveType = document.getElementById('accrual_leave_type_id');
            if (accrualLeaveType) {
                accrualLeaveType.addEventListener('change', updateAccrualInfo);
            }
            
            const employeeCheckboxes = document.querySelectorAll('input[name="employee_ids[]"]');
            employeeCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', updateAccrualInfo);
            });
            
            const accrueForAllRadios = document.querySelectorAll('input[name="accrue_for_all"]');
            accrueForAllRadios.forEach(radio => {
                radio.addEventListener('change', toggleEmployeeSelection);
            });
        });
    </script>
</body>
</html>