<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New employee | ZedBankOS</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',
                        danger: '#D83B01',
                        gray50: '#FAF9F8',
                        gray100: '#F3F2F1',
                        gray200: '#EDEBE9',
                    }
                }
            }
        }
    </script>
    <style>
        .form-input, .form-select {
            border: 1px solid #8C8C8C;
            border-radius: 4px;
            padding: 4px 10px;
            font-size: 13px;
            width: 100%;
            transition: all 0.2s;
        }
        .form-input:focus, .form-select:focus {
            outline: 2px solid #146CAA;
            border-color: #146CAA;
        }
        .input-error {
            border-color: #D83B01 !important;
            background-color: #FFF4F4 !important;
            outline: 1px solid #D83B01 !important;
        }
        .form-section { background: white; border: 1px solid #EDEBE9; border-radius: 6px; padding: 16px; margin-bottom: 12px; }
        .section-title { font-size: 14px; font-weight: 700; color: #323130; margin-bottom: 12px; border-bottom: 1px solid #F3F2F1; padding-bottom: 6px; }
        .compact-label { font-size: 11px; font-weight: 700; color: #605E5C; display: block; margin-bottom: 2px; }
        .required::after { content: ' *'; color: #D83B01; }
        .compact-table th { background-color: #F3F2F1; color: #605E5C; font-size: 11px; padding: 6px 12px; border-bottom: 1px solid #EDEBE9; text-align: left; }
        .compact-table td { padding: 4px 12px; border-bottom: 1px solid #EDEBE9; font-size: 13px; }
        
        @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
        .animate-slide-in { animation: slideIn 0.3s ease-out forwards; }
    </style>
</head>
<body class="bg-gray50 text-gray-800">
    <div id="toast-container" class="fixed top-5 right-5 z-[9999] space-y-3"></div>

    @include('accounting.partials.sidebar')

    <div class="lg:ml-64">
        @include('accounting.partials.header', ['title' => 'New employee', 'subtitle' => 'Add a new employee to the payroll'])

        <main class="p-4 max-w-5xl mx-auto">
            <form id="employeeForm" action="{{ route('admin.accounting.payroll.employees.store') }}" method="POST" novalidate>
                @csrf

                <div class="form-section">
                    <h3 class="section-title">Personal information</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div>
                            <label class="compact-label required">First name</label>
                            <input type="text" name="first_name" class="form-input" required>
                        </div>
                        <div>
                            <label class="compact-label required">Last name</label>
                            <input type="text" name="last_name" class="form-input" required>
                        </div>
                        <div>
                            <label class="compact-label required">Email address</label>
                            <input type="email" name="email" class="form-input" required>
                        </div>
                        <div>
                            <label class="compact-label">Phone number</label>
                            <input type="text" name="phone" class="form-input" placeholder="09xxxxxxxx">
                        </div>
                        <div>
                            <label class="compact-label required">Date of birth</label>
                            <input type="date" name="date_of_birth" class="form-input" required>
                        </div>
                        <div>
                            <label class="compact-label required">Gender</label>
                            <select name="gender" class="form-select" required>
                                <option value="">Select...</option>
                                <option value="male">Male</option>
                                <option value="female">Female</option>
                            </select>
                        </div>
                        <div>
                            <label class="compact-label">National ID (NRC)</label>
                            <input type="text" name="national_id" class="form-input" placeholder="xxxxxx/xx/x">
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="section-title">Employment details</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div>
                            <label class="compact-label required">Employee number</label>
                            <input type="text" name="employee_number" class="form-input" value="EMP{{ date('Ymd') }}{{ rand(10,99) }}" required>
                        </div>
                        <div>
                            <label class="compact-label required">Hire date</label>
                            <input type="date" name="hire_date" class="form-input" value="{{ date('Y-m-d') }}" required>
                        </div>
                        <div>
                            <label class="compact-label">Employment type</label>
                            <select name="employment_type" class="form-select">
                                <option value="full_time">Full time</option>
                                <option value="contract">Contract</option>
                                <option value="part_time">Part time</option>
                                <option value="casual">Casual</option>
                            </select>
                        </div>
                        
                        <div>
                           <label class="compact-label required">Leave accrual rate (Days/Month)</label>
                           <input type="number" name="leave_accrual_rate" class="form-input" value="2.00" step="1" required>
                        </div>
                        
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="section-title">Statutory IDs</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label class="compact-label">Social security (NAPSA)</label>
                            <input type="text" name="napsa_number" class="form-input">
                        </div>
                        <div>
                            <label class="compact-label">Health insurance (NHIMA)</label>
                            <input type="text" name="nhima_number" class="form-input">
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="section-title">Payment information</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div>
                            <label class="compact-label required">Payment method</label>
                            <select name="payment_method" id="payment_method" class="form-select" required onchange="toggleBankFields()">
                                <option value="cash">Cash</option>
                                <option value="bank">Bank transfer</option>
                                <option value="mobile_money">Mobile money</option>
                            </select>
                        </div>
                    </div>

                    <div id="bank_fields" class="hidden mt-4 grid grid-cols-1 md:grid-cols-2 gap-3 pt-3 border-t border-gray-50">
                        <div>
                            <label class="compact-label required">Bank name</label>
                            <input type="text" name="bank_name" id="bank_name" class="form-input">
                        </div>
                        <div>
                            <label class="compact-label required">Account number</label>
                            <input type="text" name="bank_account_number" id="bank_account_number" class="form-input">
                        </div>
                        <div>
                            <label class="compact-label required">Account holder name</label>
                            <input type="text" name="bank_account_name" id="bank_account_name" class="form-input">
                        </div>
                        <div>
                            <label class="compact-label">Bank branch</label>
                            <input type="text" name="bank_branch" class="form-input">
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <div class="flex justify-between items-center mb-3">
                        <h3 class="text-sm font-bold text-gray-700">Earnings & salary components</h3>
                        <button type="button" id="addRowBtn" class="text-primary text-xs font-bold hover:underline">+ Add row</button>
                    </div>
                    <div class="overflow-x-auto border rounded border-gray-200">
                        <table class="compact-table w-full">
                            <thead>
                                <tr>
                                    <th class="w-1/2">Earning type</th>
                                    <th>Amount (ZMW)</th>
                                    <th>Frequency</th>
                                    <th class="w-10"></th>
                                </tr>
                            </thead>
                            <tbody id="earningsBody"></tbody>
                        </table>
                    </div>
                </div>

                <div class="mt-6 flex justify-end space-x-3 border-t pt-4 pb-12">
                    <a href="{{ route('admin.accounting.payroll.employees.index') }}" class="px-4 py-2 text-sm font-bold text-gray-500">Cancel</a>
                    <button type="submit" class="bg-primary text-white px-8 py-2 rounded shadow font-bold text-sm hover:bg-opacity-90 transition">Save employee</button>
                </div>
            </form>
        </main>
    </div>

    <script>
        // --- 1. Modern Pop (Toast) System ---
        function showToast(message, type = 'error') {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            toast.className = `flex items-center p-4 rounded-lg shadow-lg border-l-4 animate-slide-in ${type === 'error' ? 'bg-red-50 border-red-600 text-red-800' : 'bg-green-50 border-green-600 text-green-800'}`;
            toast.innerHTML = `<i class="fas ${type === 'error' ? 'fa-exclamation-circle' : 'fa-check-circle'} mr-3"></i><span class="text-sm font-bold">${message}</span>`;
            container.appendChild(toast);
            setTimeout(() => { toast.style.opacity = '0'; setTimeout(() => toast.remove(), 500); }, 4000);
        }

        @if(session('success')) showToast("{{ session('success') }}", 'success'); @endif
        @if(session('error')) showToast("{{ session('error') }}", 'error'); @endif

        // --- 2. Validation & Submission Logic ---
        const form = document.getElementById('employeeForm');
        form.addEventListener('submit', function(e) {
            let isValid = true;
            let firstErrorField = null;

            // Reset styles
            form.querySelectorAll('.input-error').forEach(el => el.classList.remove('input-error'));

            // Check required fields
            form.querySelectorAll('[required]').forEach(input => {
                if (!input.value.trim()) {
                    isValid = false;
                    input.classList.add('input-error');
                    if (!firstErrorField) firstErrorField = input;
                }
            });

            if (!isValid) {
                e.preventDefault();
                showToast("Please fill in all required fields highlighted in red.");
                if (firstErrorField) {
                    firstErrorField.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    firstErrorField.focus();
                }
            }
        });

        // Clear error on input
        form.querySelectorAll('input, select').forEach(input => {
            input.addEventListener('input', function() { this.classList.remove('input-error'); });
        });

        // --- 3. Payment Toggle Logic ---
        function toggleBankFields() {
            const method = document.getElementById('payment_method').value;
            const bankDiv = document.getElementById('bank_fields');
            const fields = ['bank_name', 'bank_account_number', 'bank_account_name'];
            
            if (method === 'bank') {
                bankDiv.classList.remove('hidden');
                fields.forEach(id => document.getElementById(id).setAttribute('required', 'true'));
            } else {
                bankDiv.classList.add('hidden');
                fields.forEach(id => {
                    const el = document.getElementById(id);
                    el.removeAttribute('required');
                    el.classList.remove('input-error');
                });
            }
        }

        // --- 4. Dynamic Earnings Rows ---
        const earningTypes = @json($earningTypes);
        const container = document.getElementById('earningsBody');
        let counter = 0;

        function addRow(typeId = '', amount = '') {
            counter++;
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>
                    <select name="earnings[${counter}][type_id]" class="form-select text-xs" required>
                        <option value="">Select type</option>
                        ${earningTypes.map(t => `<option value="${t.id}" ${typeId == t.id ? 'selected' : ''}>${t.name}</option>`).join('')}
                    </select>
                </td>
                <td><input type="number" name="earnings[${counter}][amount]" class="form-input text-right" value="${amount}" step="0.01" required></td>
                <td>
                    <select name="earnings[${counter}][frequency]" class="form-select text-xs">
                        <option value="monthly">Monthly</option>
                        <option value="one_time">One time</option>
                    </select>
                </td>
                <td class="text-center">
                    <button type="button" onclick="this.closest('tr').remove()" class="text-gray-300 hover:text-red-500"><i class="fas fa-times"></i></button>
                </td>
            `;
            container.appendChild(tr);
        }

        document.getElementById('addRowBtn').addEventListener('click', () => addRow());

        window.onload = () => {
            const basic = earningTypes.find(t => t.type === 'basic' || t.name.toLowerCase().includes('basic'));
            addRow(basic ? basic.id : '', '');
        };
    </script>
</body>
</html>