<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Leave Request</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 src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.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-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);
        }
        .quickbooks-textarea {
            border: 1px solid #E1DFDD;
            border-radius: 4px;
            padding: 8px 12px;
            font-size: 14px;
            transition: border-color 0.2s;
            width: 100%;
            resize: vertical;
            min-height: 100px;
        }
        .quickbooks-textarea:focus {
            outline: none;
            border-color: #146CAA;
            box-shadow: 0 0 0 2px rgba(20, 108, 170, 0.1);
        }
        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: #323130;
            margin-bottom: 8px;
        }
        .required::after {
            content: "*";
            color: #D83B01;
            margin-left: 4px;
        }
        .balance-info {
            background-color: #F3F2F1;
            border: 1px solid #EDEBE9;
            border-radius: 4px;
            padding: 12px;
            margin-top: 8px;
        }
        .balance-value {
            font-weight: 600;
            color: #107C10;
        }
        .flatpickr-input {
            background-color: white !important;
        }
    </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">New Leave Request</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>
                        <a href="{{ route('admin.accounting.payroll.leave.requests.index') }}" class="hover:text-primary">Leave Requests</a>
                        <span>/</span>
                        <span class="text-gray900">New Request</span>
                    </nav>
                </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($errors->any())
                <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>
                            <div>
                                <span class="text-red-800 font-medium">Please fix the following errors:</span>
                                <ul class="text-red-700 text-sm mt-1">
                                    @foreach($errors->all() as $error)
                                    <li class="ml-4">{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        </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

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Form -->
                <div class="lg:col-span-2">
                    <div class="bg-white rounded-lg border border-gray200">
                        <div class="p-6 border-b border-gray200">
                            <h2 class="text-lg font-semibold text-gray900">Leave Request Information</h2>
                            <p class="text-gray600 text-sm mt-1">Fill in the details below to submit a new leave request</p>
                        </div>
                        
                        <form method="POST" action="{{ route('admin.accounting.payroll.leave.requests.store') }}" class="p-6">
                            @csrf
                            
                            <div class="space-y-6">
                                <!-- Employee Selection -->
                                <div>
                                    <label for="employee_id" class="form-label required">Employee</label>
                                    <select name="employee_id" 
                                            id="employee_id"
                                            class="quickbooks-input"
                                            required
                                            onchange="loadLeaveBalance()">
                                        <option value="">Select Employee</option>
                                        @foreach($employees as $employee)
                                        <option value="{{ $employee->id }}" {{ old('employee_id') == $employee->id ? 'selected' : '' }}>
                                            {{ $employee->full_name }} ({{ $employee->employee_number }})
                                        </option>
                                        @endforeach
                                    </select>
                                </div>

                                <!-- Leave Type Selection -->
                                <div>
                                    <label for="leave_type_id" class="form-label required">Leave Type</label>
                                    <select name="leave_type_id" 
                                            id="leave_type_id"
                                            class="quickbooks-input"
                                            required
                                            onchange="loadLeaveBalance()">
                                        <option value="">Select Leave Type</option>
                                        @foreach($leaveTypes as $type)
                                        <option value="{{ $type->id }}" {{ old('leave_type_id') == $type->id ? 'selected' : '' }}>
                                            {{ $type->name }} 
                                            @if($type->max_days_per_year)
                                                ({{ $type->max_days_per_year }} days/year)
                                            @endif
                                        </option>
                                        @endforeach
                                    </select>
                                </div>

                                <!-- Leave Balance Information -->
                                <div id="balanceInfo" class="balance-info hidden">
                                    <div class="flex items-center justify-between">
                                        <div>
                                            <div class="text-sm text-gray600">Available Balance</div>
                                            <div class="text-lg font-semibold text-gray900" id="balanceValue">0 days</div>
                                        </div>
                                        <div>
                                            <div class="text-sm text-gray600">Max Allowed</div>
                                            <div class="text-lg font-semibold text-gray900" id="maxAllowed">0 days</div>
                                        </div>
                                    </div>
                                    <div class="mt-2 text-xs text-gray500" id="balanceDetails">
                                        Loading balance information...
                                    </div>
                                </div>

                                <!-- Date Range -->
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="start_date" class="form-label required">Start Date</label>
                                        <input type="text" 
                                               name="start_date" 
                                               id="start_date"
                                               class="quickbooks-input flatpickr-input"
                                               value="{{ old('start_date') }}"
                                               required>
                                    </div>
                                    <div>
                                        <label for="end_date" class="form-label required">End Date</label>
                                        <input type="text" 
                                               name="end_date" 
                                               id="end_date"
                                               class="quickbooks-input flatpickr-input"
                                               value="{{ old('end_date') }}"
                                               required>
                                    </div>
                                </div>

                                <!-- Duration Calculation -->
                                <div>
                                    <div class="flex items-center justify-between mb-2">
                                        <label class="form-label">Duration</label>
                                        <button type="button" 
                                                onclick="calculateDuration()"
                                                class="text-sm text-primary hover:text-primary/80 font-medium">
                                            <i class="fas fa-calculator mr-1"></i>Calculate Duration
                                        </button>
                                    </div>
                                    <div class="balance-info">
                                        <div class="text-center">
                                            <div class="text-2xl font-bold text-primary" id="durationValue">0 days</div>
                                            <div class="text-sm text-gray600 mt-1" id="workingDaysInfo"></div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Reason -->
                                <div>
                                    <label for="reason" class="form-label required">Reason for Leave</label>
                                    <textarea name="reason" 
                                              id="reason"
                                              class="quickbooks-textarea"
                                              placeholder="Please provide a reason for your leave request..."
                                              required>{{ old('reason') }}</textarea>
                                </div>

                                <!-- Requested By -->
                                <div>
                                    <label for="requested_by" class="form-label">Requested By</label>
                                    <select name="requested_by" 
                                            id="requested_by"
                                            class="quickbooks-input">
                                        <option value="{{ auth()->id() }}">{{ auth()->user()->name }} (You)</option>
                                        @foreach($company->users as $user)
                                            @if($user->id != auth()->id())
                                            <option value="{{ $user->id }}" {{ old('requested_by') == $user->id ? 'selected' : '' }}>
                                                {{ $user->name }}
                                            </option>
                                            @endif
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            <div class="flex items-center justify-between pt-6 mt-6 border-t border-gray200">
                                <a href="{{ route('admin.accounting.payroll.leave.requests.index') }}" 
                                   class="px-4 py-2 text-gray700 hover:bg-gray100 rounded text-sm font-medium">
                                    Cancel
                                </a>
                                <button type="submit" 
                                        id="submitBtn"
                                        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-paper-plane"></i>
                                    Submit Leave Request
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Information Panel -->
                <div>
                    <div class="bg-white rounded-lg border border-gray200">
                        <div class="p-6 border-b border-gray200">
                            <h2 class="text-lg font-semibold text-gray900">Important Information</h2>
                        </div>
                        <div class="p-6">
                            <div class="space-y-4">
                                <div class="flex items-start space-x-3">
                                    <div class="w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0 mt-1">
                                        <i class="fas fa-info text-blue-600 text-xs"></i>
                                    </div>
                                    <div>
                                        <h4 class="text-sm font-medium text-gray900">Leave Balance Check</h4>
                                        <p class="text-xs text-gray600 mt-1">The system will automatically check if the employee has sufficient leave balance before approval.</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-start space-x-3">
                                    <div class="w-6 h-6 rounded-full bg-yellow-100 flex items-center justify-center flex-shrink-0 mt-1">
                                        <i class="fas fa-clock text-yellow-600 text-xs"></i>
                                    </div>
                                    <div>
                                        <h4 class="text-sm font-medium text-gray900">Approval Process</h4>
                                        <p class="text-xs text-gray600 mt-1">Leave requests may require approval based on leave type settings. You'll be notified once approved.</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-start space-x-3">
                                    <div class="w-6 h-6 rounded-full bg-green-100 flex items-center justify-center flex-shrink-0 mt-1">
                                        <i class="fas fa-calendar-check text-green-600 text-xs"></i>
                                    </div>
                                    <div>
                                        <h4 class="text-sm font-medium text-gray900">Paid vs Unpaid</h4>
                                        <p class="text-xs text-gray600 mt-1">Some leave types may be unpaid. Check the leave type settings for payment information.</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-start space-x-3">
                                    <div class="w-6 h-6 rounded-full bg-purple-100 flex items-center justify-center flex-shrink-0 mt-1">
                                        <i class="fas fa-exclamation-triangle text-purple-600 text-xs"></i>
                                    </div>
                                    <div>
                                        <h4 class="text-sm font-medium text-gray900">Important Notes</h4>
                                        <ul class="text-xs text-gray600 mt-1 list-disc list-inside space-y-1">
                                            <li>Ensure dates do not conflict with existing leave</li>
                                            <li>Submit requests at least 3 days in advance</li>
                                            <li>Emergency leave requires manager approval</li>
                                            <li>Keep supporting documents if required</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Initialize date pickers
        document.addEventListener('DOMContentLoaded', function() {
            // Date pickers
            flatpickr('#start_date', {
                dateFormat: 'Y-m-d',
                minDate: 'today',
                onChange: function(selectedDates, dateStr) {
                    const endDatePicker = document.querySelector('#end_date')._flatpickr;
                    if (endDatePicker && dateStr) {
                        endDatePicker.set('minDate', dateStr);
                    }
                    calculateDuration();
                }
            });
            
            flatpickr('#end_date', {
                dateFormat: 'Y-m-d',
                minDate: 'today',
                onChange: function() {
                    calculateDuration();
                }
            });
            
            // Load initial balance if employee and leave type are preselected
            const employeeId = document.getElementById('employee_id').value;
            const leaveTypeId = document.getElementById('leave_type_id').value;
            
            if (employeeId && leaveTypeId) {
                loadLeaveBalance();
            }
            
            // Auto-hide alerts after 5 seconds
            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);
        });
        
        // Calculate duration between dates
        function calculateDuration() {
            const startDate = document.getElementById('start_date').value;
            const endDate = document.getElementById('end_date').value;
            
            if (startDate && endDate) {
                const start = new Date(startDate);
                const end = new Date(endDate);
                
                // Calculate difference in days (inclusive)
                const diffTime = Math.abs(end - start);
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
                
                // Update display
                document.getElementById('durationValue').textContent = diffDays + ' days';
                
                // Show working days info
                const workingDays = calculateWorkingDays(start, end);
                document.getElementById('workingDaysInfo').textContent = 
                    `Includes ${workingDays} working days`;
            } else {
                document.getElementById('durationValue').textContent = '0 days';
                document.getElementById('workingDaysInfo').textContent = '';
            }
        }
        
        // Calculate working days (Monday to Friday)
        function calculateWorkingDays(startDate, endDate) {
            let count = 0;
            const current = new Date(startDate);
            
            while (current <= endDate) {
                const dayOfWeek = current.getDay();
                // Skip weekends (0 = Sunday, 6 = Saturday)
                if (dayOfWeek !== 0 && dayOfWeek !== 6) {
                    count++;
                }
                current.setDate(current.getDate() + 1);
            }
            
            return count;
        }
        
        // Load leave balance for selected employee and leave type
        async function loadLeaveBalance() {
            const employeeId = document.getElementById('employee_id').value;
            const leaveTypeId = document.getElementById('leave_type_id').value;
            const balanceInfo = document.getElementById('balanceInfo');
            
            if (!employeeId || !leaveTypeId) {
                balanceInfo.classList.add('hidden');
                return;
            }
            
            // Show loading state
            balanceInfo.classList.remove('hidden');
            document.getElementById('balanceValue').textContent = 'Loading...';
            document.getElementById('maxAllowed').textContent = 'Loading...';
            document.getElementById('balanceDetails').textContent = 'Fetching balance information...';
            
            try {
                const response = await fetch(`{{ url('/') }}/admin/accounting/payroll/leave/balance/${employeeId}/${leaveTypeId}`);
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('balanceValue').textContent = data.balance + ' days';
                    document.getElementById('maxAllowed').textContent = data.total_accrued + ' days accrued';
                    
                    const details = [];
                    if (data.balance > 0) {
                        details.push(`${data.total_taken} days taken`);
                    }
                    
                    document.getElementById('balanceDetails').textContent = details.join(' • ');
                    
                    // Update submit button state based on balance
                    const submitBtn = document.getElementById('submitBtn');
                    if (data.balance <= 0) {
                        submitBtn.disabled = true;
                        submitBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Insufficient Balance';
                        submitBtn.classList.remove('bg-primary');
                        submitBtn.classList.add('bg-gray-400', 'cursor-not-allowed');
                    } else {
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Submit Leave Request';
                        submitBtn.classList.remove('bg-gray-400', 'cursor-not-allowed');
                        submitBtn.classList.add('bg-primary');
                    }
                } else {
                    throw new Error(data.message || 'Failed to load balance');
                }
            } catch (error) {
                console.error('Error loading leave balance:', error);
                document.getElementById('balanceValue').textContent = 'Error';
                document.getElementById('maxAllowed').textContent = 'Error';
                document.getElementById('balanceDetails').textContent = 'Failed to load balance information';
            }
        }
        
        // Form validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const startDate = document.getElementById('start_date').value;
            const endDate = document.getElementById('end_date').value;
            
            if (startDate && endDate) {
                const start = new Date(startDate);
                const end = new Date(endDate);
                
                if (end < start) {
                    e.preventDefault();
                    alert('End date must be after start date');
                    return false;
                }
            }
            
            // Show loading state on submit button
            const submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Submitting...';
        });
    </script>
</body>
</html>