window.HRApp = (function() {
    let currentUser = null;
    let employees = [];
    let advances = [];
    let payrolls = [];
    let accounts = [];
    let projects = [];
    let transactions = [];
    let users = [];

    // System Accounts IDs
    let advancesAccountId = null;
    let salariesExpenseAccountId = null;
    let accruedSalariesAccountId = null;

    async function init() {
        try {
            const storedUser = sessionStorage.getItem('currentUser');
            if (storedUser) {
                currentUser = JSON.parse(storedUser);
                document.getElementById('current-username').innerText = currentUser.username;
                
                // Hide login, show app
                document.getElementById('view-login').classList.remove('active');
                document.getElementById('app-layout').style.display = 'flex';
                
                await loadData();
                setupNavigation();
                
                // Render initial view
                showView('hr-dashboard');
                updateDashboardStats();
            } else {
                // Not logged in
                window.location.href = 'index.html';
            }
        } catch(e) {
            console.error('Error init HR:', e);
        }
    }

    async function loadData() {
        if (!window.DB || typeof window.DB.getAll !== 'function') {
            console.log('Waiting for DB...');
            setTimeout(loadData, 500);
            return;
        }

        accounts = (await window.DB.getAll('accounts')) || [];
        projects = (await window.DB.getAll('projects')) || [];
        users = (await window.DB.getAll('users')) || [];
        transactions = (await window.DB.getAll('transactions')) || [];
        
        employees = (await window.DB.getAll('employees')) || [];
        advances = (await window.DB.getAll('advances')) || [];
        payrolls = (await window.DB.getAll('payrolls')) || [];

        await setupSystemAccounts();
    }

    async function setupSystemAccounts() {
        let advAcc = accounts.find(a => a.name === 'سلف العاملين');
        if (!advAcc) {
            try { 
                const id = Date.now();
                await window.DB.add('accounts', { id, name: 'سلف العاملين', type: 'أصول متداولة', balance: 0, parent_id: '' }); 
                advancesAccountId = id;
            } catch(e) {}
        } else { advancesAccountId = advAcc.id; }

        let expAcc = accounts.find(a => a.name === 'مصروفات الرواتب والأجور');
        if (!expAcc) {
            try { 
                const id = Date.now() + 1;
                await window.DB.add('accounts', { id, name: 'مصروفات الرواتب والأجور', type: 'مصروفات', balance: 0, parent_id: '' }); 
                salariesExpenseAccountId = id;
            } catch(e) {}
        } else { salariesExpenseAccountId = expAcc.id; }

        let accAcc = accounts.find(a => a.name === 'رواتب وأجور مستحقة');
        if (!accAcc) {
            try { 
                const id = Date.now() + 2;
                await window.DB.add('accounts', { id, name: 'رواتب وأجور مستحقة', type: 'خصوم متداولة', balance: 0, parent_id: '' }); 
                accruedSalariesAccountId = id;
            } catch(e) {}
        } else { accruedSalariesAccountId = accAcc.id; }
        
        accounts = (await window.DB.getAll('accounts')) || [];
    }

    function setupNavigation() {
        document.querySelectorAll('.sidebar ul li a').forEach(link => {
            link.addEventListener('click', (e) => {
                if(e.target.getAttribute('href') === 'index.html') return;
                e.preventDefault();
                document.querySelectorAll('.sidebar ul li a').forEach(l => l.classList.remove('active'));
                e.target.classList.add('active');
                const targetView = e.target.dataset.view;
                if(targetView) showView(targetView);
            });
        });
    }

    function showView(viewId) {
        document.querySelectorAll('.content-area .view').forEach(v => v.classList.remove('active'));
        const el = document.getElementById('view-' + viewId);
        if (el) el.classList.add('active');

        if (viewId === 'hr-employees') renderEmployees();
        else if (viewId === 'hr-advances') renderAdvances();
        else if (viewId === 'hr-payroll') preparePayrollView();
        else if (viewId === 'hr-ledger') prepareLedgerView();
        else if (viewId === 'hr-dashboard') updateDashboardStats();
    }

    function updateDashboardStats() {
        document.getElementById('stat-emp-count').innerText = employees.length;
        document.getElementById('stat-adv-active').innerText = advances.filter(a => a.status === 'active').length;
        document.getElementById('stat-payroll-total').innerText = payrolls.reduce((sum, p) => sum + (parseFloat(p.net_total) || 0), 0).toFixed(2);
    }

    // --- User Roles Helpers ---
    function getVisibleProjects() {
        if (currentUser.role === 'مدير عام') return projects;
        if (currentUser.role === 'محاسب' && currentUser.allowed_projects) {
            return projects.filter(p => currentUser.allowed_projects.includes(parseInt(p.id)));
        } else if (currentUser.role === 'مهندس' && currentUser.project_id) {
            return projects.filter(p => parseInt(p.id) === parseInt(currentUser.project_id));
        }
        return projects;
    }

    function getVisibleEmployees() {
        if (currentUser.role === 'مدير عام') return employees;
        const visibleProjects = getVisibleProjects().map(p => p.id);
        return employees.filter(e => visibleProjects.includes(parseInt(e.project_id)));
    }

    // --- EMPLOYEES ---
    function renderEmployees() {
        const tbody = document.getElementById('hr-employees-tbody');
        if (!tbody) return;
        tbody.innerHTML = '';
        
        const visibleEmployees = getVisibleEmployees();

        visibleEmployees.forEach(emp => {
            const basic = parseFloat(emp.basic_salary) || 0;
            const housing = parseFloat(emp.housing_allowance) || 0;
            const transport = parseFloat(emp.transport_allowance) || 0;
            const leaves = parseFloat(emp.leave_balance) || 0;

            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${emp.name || ''}</td>
                <td>${(projects.find(p => p.id == emp.project_id) || {}).name || '-'}</td>
                <td>${emp.status === 'active' ? '<span style="color:var(--success)">نشط</span>' : '<span style="color:var(--danger)">غير نشط</span>'}</td>
                <td>${basic.toFixed(2)}</td>
                <td>${housing.toFixed(2)}</td>
                <td>${transport.toFixed(2)}</td>
                <td>${leaves}</td>
                <td>
                    <button class="action-btn btn-edit" onclick="HRApp.openEmployeeModal(${emp.id})">تعديل</button>
                    <button class="action-btn btn-delete" onclick="HRApp.deleteEmployee(${emp.id})">حذف</button>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    function openEmployeeModal(id = null) {
        const pSelect = document.getElementById('hr-emp-project');
        pSelect.innerHTML = '<option value="">-- بدون مشروع --</option>';
        getVisibleProjects().forEach(p => pSelect.innerHTML += `<option value="${p.id}">${p.name}</option>`);

        if (id) {
            const emp = employees.find(e => e.id === id);
            if (emp) {
                document.getElementById('hr-employee-id').value = emp.id;
                document.getElementById('hr-emp-name').value = emp.name || '';
                document.getElementById('hr-emp-project').value = emp.project_id || '';
                document.getElementById('hr-emp-basic').value = emp.basic_salary || 0;
                document.getElementById('hr-emp-housing').value = emp.housing_allowance || 0;
                document.getElementById('hr-emp-transport').value = emp.transport_allowance || 0;
                document.getElementById('hr-emp-leaves').value = emp.leave_balance || 0;
                document.getElementById('hr-emp-status').value = emp.status || 'active';
                document.getElementById('hr-employee-modal-title').innerText = 'تعديل موظف';
            }
        } else {
            document.getElementById('hr-employee-id').value = '';
            document.getElementById('hr-emp-name').value = '';
            document.getElementById('hr-emp-project').value = '';
            document.getElementById('hr-emp-basic').value = 0;
            document.getElementById('hr-emp-housing').value = 0;
            document.getElementById('hr-emp-transport').value = 0;
            document.getElementById('hr-emp-leaves').value = 0;
            document.getElementById('hr-emp-status').value = 'active';
            document.getElementById('hr-employee-modal-title').innerText = 'إضافة موظف جديد';
        }
        document.getElementById('hr-employee-modal').style.display = 'flex';
    }

    function closeEmployeeModal() { document.getElementById('hr-employee-modal').style.display = 'none'; }

    async function saveEmployee() {
        const id = document.getElementById('hr-employee-id').value;
        const nameVal = document.getElementById('hr-emp-name').value.trim();
        if (!nameVal) return alert('يرجى إدخال اسم الموظف');

        document.getElementById('hr-employee-modal').style.display = 'none';
        
        const data = {
            name: nameVal,
            project_id: document.getElementById('hr-emp-project').value,
            basic_salary: parseFloat(document.getElementById('hr-emp-basic').value) || 0,
            housing_allowance: parseFloat(document.getElementById('hr-emp-housing').value) || 0,
            transport_allowance: parseFloat(document.getElementById('hr-emp-transport').value) || 0,
            leave_balance: parseFloat(document.getElementById('hr-emp-leaves').value) || 0,
            status: document.getElementById('hr-emp-status').value
        };

        if (id) {
            data.id = parseInt(id);
            await window.DB.update('employees', data);
        } else {
            data.id = Date.now();
            await window.DB.add('employees', data);
        }

        employees = (await window.DB.getAll('employees')) || [];
        renderEmployees();
        updateDashboardStats();
    }

    async function deleteEmployee(id) {
        if (!confirm('هل أنت متأكد من حذف هذا الموظف؟')) return;
        await window.DB.delete('employees', id);
        employees = (await window.DB.getAll('employees')) || [];
        renderEmployees();
        updateDashboardStats();
    }

    // --- ADVANCES ---
    function renderAdvances() {
        const tbody = document.getElementById('hr-advances-tbody');
        if (!tbody) return;
        tbody.innerHTML = '';
        
        const visibleEmployees = getVisibleEmployees();
        const empIds = visibleEmployees.map(e => String(e.id));
        const visibleAdvances = advances.filter(a => empIds.includes(String(a.employee_id)));

        visibleAdvances.forEach(adv => {
            const emp = employees.find(e => e.id == adv.employee_id) || {};
            const amount = parseFloat(adv.amount) || 0;
            const paid = parseFloat(adv.paid_amount) || 0;
            const remain = amount - paid;
            const installment = amount / (adv.installments || 1);

            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${adv.date}</td>
                <td>${emp.name || 'مجهول'}</td>
                <td>${amount.toFixed(2)}</td>
                <td>${installment.toFixed(2)}</td>
                <td style="color:var(--success);">${paid.toFixed(2)}</td>
                <td style="color:var(--danger);">${remain.toFixed(2)}</td>
                <td>${adv.status === 'completed' ? '<span style="color:var(--success)">مسدد بالكامل</span>' : '<span style="color:var(--warning)">ساري</span>'}</td>
                <td>
                    <button class="action-btn btn-delete" onclick="HRApp.deleteAdvance(${adv.id})">حذف</button>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    function openAdvanceModal() {
        const eSelect = document.getElementById('hr-adv-employee');
        eSelect.innerHTML = '<option value="">اختر الموظف...</option>';
        getVisibleEmployees().filter(e => e.status === 'active').forEach(e => {
            eSelect.innerHTML += `<option value="${e.id}">${e.name}</option>`;
        });

        const tSelect = document.getElementById('hr-adv-treasury');
        tSelect.innerHTML = '<option value="">اختر الخزينة / البنك...</option>';
        const treasuryAccounts = accounts.filter(a => a.name.includes('خزين') || a.name.includes('صندوق') || a.name.includes('بنك'));
        treasuryAccounts.forEach(a => {
            tSelect.innerHTML += `<option value="${a.id}">${a.name}</option>`;
        });

        document.getElementById('hr-adv-id').value = '';
        document.getElementById('hr-adv-amount').value = '';
        document.getElementById('hr-adv-date').value = new Date().toISOString().split('T')[0];
        document.getElementById('hr-adv-month').value = '';
        document.getElementById('hr-adv-installments').value = 1;

        document.getElementById('hr-advance-modal').style.display = 'flex';
    }

    function closeAdvanceModal() { document.getElementById('hr-advance-modal').style.display = 'none'; }

    async function saveAdvance() {
        const empId = document.getElementById('hr-adv-employee').value;
        const amount = parseFloat(document.getElementById('hr-adv-amount').value);
        const treasuryId = document.getElementById('hr-adv-treasury').value;
        
        if (!empId || !amount || !treasuryId) return alert('يرجى اختيار الموظف والمبلغ وتحديد الخزينة');

        document.getElementById('hr-advance-modal').style.display = 'none';
        
        const data = {
            id: Date.now(),
            employee_id: empId,
            amount: amount,
            date: document.getElementById('hr-adv-date').value,
            start_month: document.getElementById('hr-adv-month').value,
            installments: parseInt(document.getElementById('hr-adv-installments').value) || 1,
            paid_amount: 0,
            status: 'active'
        };

        // Auto-Journal: Dr Advances, Cr Treasury
        const treasuryAcc = accounts.find(a => a.id == treasuryId);
        const emp = employees.find(e => e.id == empId);
        
        const transId = Date.now() + 1;
        const transData = {
            id: transId,
            date: data.date,
            description: `صرف سلفة نقدية للموظف: ${emp.name}`,
            type: 'hr_advance',
            reference_id: data.id,
            details: JSON.stringify([
                { account_id: advancesAccountId, debit: amount, credit: 0 },
                { account_id: treasuryId, debit: 0, credit: amount }
            ])
        };

        await window.DB.add('advances', data);
        await window.DB.add('transactions', transData);

        // Update Account Balances
        if (advancesAccountId) await updateAccountBalance(advancesAccountId, amount, 0);
        await updateAccountBalance(treasuryId, 0, amount);

        advances = (await window.DB.getAll('advances')) || [];
        transactions = (await window.DB.getAll('transactions')) || [];
        renderAdvances();
        updateDashboardStats();
        alert('تم حفظ السلفة وإنشاء سند الصرف بنجاح');
    }

    async function deleteAdvance(id) {
        if (!confirm('سيتم حذف السلفة وقيدها المرتبط. هل أنت متأكد؟')) return;
        
        const trans = transactions.find(t => t.type === 'hr_advance' && parseInt(t.reference_id) === parseInt(id));
        if (trans) {
            await window.DB.delete('transactions', trans.id);
            // Reverse balances
            const details = JSON.parse(trans.details || '[]');
            for (let d of details) {
                await updateAccountBalance(d.account_id, d.credit, d.debit); // Reverse
            }
        }

        await window.DB.delete('advances', id);
        advances = (await window.DB.getAll('advances')) || [];
        transactions = (await window.DB.getAll('transactions')) || [];
        renderAdvances();
        updateDashboardStats();
    }

    async function updateAccountBalance(accId, debit, credit) {
        if (!accId) return;
        let acc = accounts.find(a => a.id == accId);
        if (acc) {
            acc.balance = (parseFloat(acc.balance) || 0) + parseFloat(debit) - parseFloat(credit);
            await window.DB.update('accounts', acc);
        }
    }

    // --- PAYROLL ---
    function preparePayrollView() {
        const pSelect = document.getElementById('payroll-project-filter');
        pSelect.innerHTML = '<option value="all">جميع المشاريع</option>';
        getVisibleProjects().forEach(p => pSelect.innerHTML += `<option value="${p.id}">${p.name}</option>`);

        document.getElementById('payroll-month').value = new Date().toISOString().slice(0,7);
        document.getElementById('hr-payroll-tbody').innerHTML = '<tr><td colspan="8" style="text-align:center;">اختر الشهر والمشروع ثم اضغط "توليد المسير"</td></tr>';
    }

    window.currentPayrollGrid = [];

    function generatePayroll() {
        const month = document.getElementById('payroll-month').value;
        const projectFilter = document.getElementById('payroll-project-filter').value;
        if (!month) return alert('يرجى تحديد الشهر');

        let targetEmployees = getVisibleEmployees().filter(e => e.status === 'active');
        if (projectFilter !== 'all') {
            targetEmployees = targetEmployees.filter(e => String(e.project_id) === String(projectFilter));
        }

        const tbody = document.getElementById('hr-payroll-tbody');
        tbody.innerHTML = '';
        window.currentPayrollGrid = [];

        targetEmployees.forEach(emp => {
            const basic = parseFloat(emp.basic_salary) || 0;
            const housing = parseFloat(emp.housing_allowance) || 0;
            const transport = parseFloat(emp.transport_allowance) || 0;
            const totalFixed = basic + housing + transport;
            
            // Calculate Advance Installment
            let advanceDeduction = 0;
            const empAdvances = advances.filter(a => a.employee_id == emp.id && a.status === 'active');
            empAdvances.forEach(adv => {
                const amount = parseFloat(adv.amount) || 0;
                const paid = parseFloat(adv.paid_amount) || 0;
                const remain = amount - paid;
                const installment = amount / (adv.installments || 1);
                advanceDeduction += Math.min(installment, remain); // Don't deduct more than remaining
            });

            const rowId = 'pr_' + emp.id;
            
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${emp.name}</td>
                <td>${totalFixed.toFixed(2)}</td>
                <td><input type="number" id="${rowId}_bonus" value="0" min="0" oninput="HRApp.recalcPayrollRow(${emp.id})" style="width:70px; padding:4px;"></td>
                <td><input type="number" id="${rowId}_deduction" value="0" min="0" oninput="HRApp.recalcPayrollRow(${emp.id})" style="width:70px; padding:4px;"></td>
                <td><input type="number" id="${rowId}_leaves" value="0" min="0" max="${emp.leave_balance || 0}" oninput="HRApp.recalcPayrollRow(${emp.id})" title="رصيد الإجازات المتاح: ${emp.leave_balance || 0}" style="width:70px; padding:4px;"></td>
                <td><input type="number" id="${rowId}_absence" value="0" min="0" oninput="HRApp.recalcPayrollRow(${emp.id})" style="width:70px; padding:4px;"></td>
                <td style="color:var(--danger)">${advanceDeduction.toFixed(2)}</td>
                <td id="${rowId}_net" style="font-weight:bold; color:var(--success);">${(totalFixed - advanceDeduction).toFixed(2)}</td>
            `;
            tbody.appendChild(tr);

            window.currentPayrollGrid.push({
                employee: emp,
                totalFixed: totalFixed,
                advanceDeduction: advanceDeduction,
                bonus: 0,
                deduction: 0,
                leaves: 0,
                absence: 0,
                net: totalFixed - advanceDeduction
            });
        });
        recalcPayrollTotal();
    }

    function recalcPayrollRow(empId) {
        const rowId = 'pr_' + empId;
        const entry = window.currentPayrollGrid.find(g => g.employee.id === empId);
        if (!entry) return;

        entry.bonus = parseFloat(document.getElementById(rowId + '_bonus').value) || 0;
        entry.deduction = parseFloat(document.getElementById(rowId + '_deduction').value) || 0;
        entry.leaves = parseFloat(document.getElementById(rowId + '_leaves').value) || 0;
        entry.absence = parseFloat(document.getElementById(rowId + '_absence').value) || 0;

        const dailyRate = entry.totalFixed / 30; // Assuming 30 days
        const absenceDeduction = entry.absence * dailyRate;

        entry.net = entry.totalFixed + entry.bonus - entry.deduction - absenceDeduction - entry.advanceDeduction;
        document.getElementById(rowId + '_net').innerText = entry.net.toFixed(2);
        
        recalcPayrollTotal();
    }

    function recalcPayrollTotal() {
        let tBasic = 0, tBonus = 0, tDed = 0, tLeaves = 0, tAbs = 0, tAdv = 0, tNet = 0;
        window.currentPayrollGrid.forEach(entry => {
            tBasic += entry.totalFixed;
            tBonus += entry.bonus;
            tDed += entry.deduction;
            tLeaves += entry.leaves;
            tAbs += entry.absence;
            tAdv += entry.advanceDeduction;
            tNet += entry.net;
        });
        document.getElementById('pr-total-basic').innerText = tBasic.toFixed(2);
        document.getElementById('pr-total-bonus').innerText = tBonus.toFixed(2);
        document.getElementById('pr-total-deduction').innerText = tDed.toFixed(2);
        document.getElementById('pr-total-leaves').innerText = tLeaves.toFixed(2);
        document.getElementById('pr-total-absence').innerText = tAbs.toFixed(2);
        document.getElementById('pr-total-advances').innerText = tAdv.toFixed(2);
        document.getElementById('pr-total-net').innerText = tNet.toFixed(2);
    }

    async function savePayroll() {
        if (!window.currentPayrollGrid || window.currentPayrollGrid.length === 0) return alert('يرجى توليد المسير أولاً');
        const month = document.getElementById('payroll-month').value;
        const projectFilter = document.getElementById('payroll-project-filter').value;
        
        if (!confirm('هل أنت متأكد من اعتماد هذا المسير وإنشاء القيود المحاسبية؟')) return;

        const pid = Date.now();
        let totalNet = 0;
        let totalAdvances = 0;

        for (const entry of window.currentPayrollGrid) {
            totalNet += entry.net;
            totalAdvances += entry.advanceDeduction;

            // Update Employee Leaves
            if (entry.leaves > 0) {
                entry.employee.leave_balance -= entry.leaves;
                await window.DB.update('employees', entry.employee);
            }

            // Update Advances Paid Amount
            if (entry.advanceDeduction > 0) {
                let deductionLeft = entry.advanceDeduction;
                const empAdvances = advances.filter(a => a.employee_id == entry.employee.id && a.status === 'active');
                for (const adv of empAdvances) {
                    if (deductionLeft <= 0) break;
                    const amount = parseFloat(adv.amount) || 0;
                    const paid = parseFloat(adv.paid_amount) || 0;
                    const remain = amount - paid;
                    const toDeduct = Math.min(deductionLeft, remain);
                    
                    adv.paid_amount = paid + toDeduct;
                    if (adv.paid_amount >= amount) adv.status = 'completed';
                    await window.DB.update('advances', adv);
                    deductionLeft -= toDeduct;
                }
            }
        }

        const totalExpense = totalNet + totalAdvances; // Total Dr. Expense
        const projName = projectFilter === 'all' ? 'جميع المشاريع' : projects.find(p => String(p.id) === String(projectFilter)).name;

        // Auto-Journal for Payroll Approval
        const transId = Date.now() + 1;
        const transData = {
            id: transId,
            date: new Date().toISOString().split('T')[0],
            description: `استحقاق رواتب شهر ${month} - مشروع: ${projName}`,
            type: 'hr_payroll_approval',
            reference_id: pid,
            details: JSON.stringify([
                { account_id: salariesExpenseAccountId, debit: totalExpense, credit: 0 },
                { account_id: accruedSalariesAccountId, debit: 0, credit: totalNet },
                { account_id: advancesAccountId, debit: 0, credit: totalAdvances }
            ])
        };

        const payrollData = {
            id: pid,
            month: month,
            project_id: projectFilter,
            grid: JSON.stringify(window.currentPayrollGrid),
            net_total: totalNet,
            date: new Date().toISOString().split('T')[0],
            status: 'approved'
        };

        await window.DB.add('payrolls', payrollData);
        await window.DB.add('transactions', transData);

        // Update Balances
        await updateAccountBalance(salariesExpenseAccountId, totalExpense, 0);
        await updateAccountBalance(accruedSalariesAccountId, 0, totalNet);
        await updateAccountBalance(advancesAccountId, 0, totalAdvances);

        employees = (await window.DB.getAll('employees')) || [];
        advances = (await window.DB.getAll('advances')) || [];
        payrolls = (await window.DB.getAll('payrolls')) || [];
        transactions = (await window.DB.getAll('transactions')) || [];
        
        updateDashboardStats();
        
        // Open Pay Modal
        document.getElementById('pay-payroll-month').value = month;
        document.getElementById('pay-payroll-amount').value = totalNet;
        document.getElementById('pay-payroll-amount-display').value = totalNet.toFixed(2);
        
        const tSelect = document.getElementById('pay-payroll-treasury');
        tSelect.innerHTML = '<option value="">اختر الخزينة / البنك...</option>';
        const treasuryAccounts = accounts.filter(a => a.name.includes('خزين') || a.name.includes('صندوق') || a.name.includes('بنك'));
        treasuryAccounts.forEach(a => {
            tSelect.innerHTML += `<option value="${a.id}">${a.name}</option>`;
        });
        
        document.getElementById('hr-pay-payroll-modal').style.display = 'flex';
        document.getElementById('hr-payroll-tbody').innerHTML = '<tr><td colspan="8" style="text-align:center;">تم اعتماد المسير بنجاح.</td></tr>';
        window.currentPayrollGrid = [];
    }

    async function executePayPayroll() {
        const amount = parseFloat(document.getElementById('pay-payroll-amount').value);
        const treasuryId = document.getElementById('pay-payroll-treasury').value;
        const month = document.getElementById('pay-payroll-month').value;
        
        if (!treasuryId) return alert('يرجى اختيار الخزينة');

        // Auto-Journal: Dr Accrued Salaries, Cr Treasury
        const transId = Date.now();
        const transData = {
            id: transId,
            date: new Date().toISOString().split('T')[0],
            description: `سداد رواتب شهر ${month} نقداً`,
            type: 'hr_payroll_payment',
            reference_id: transId,
            details: JSON.stringify([
                { account_id: accruedSalariesAccountId, debit: amount, credit: 0 },
                { account_id: treasuryId, debit: 0, credit: amount }
            ])
        };

        await window.DB.add('transactions', transData);
        await updateAccountBalance(accruedSalariesAccountId, amount, 0);
        await updateAccountBalance(treasuryId, 0, amount);
        
        transactions = (await window.DB.getAll('transactions')) || [];
        document.getElementById('hr-pay-payroll-modal').style.display = 'none';
        alert('تم صرف المسير وتسجيل قيد السداد بنجاح');
    }

    // --- LEDGER ---
    function prepareLedgerView() {
        const eSelect = document.getElementById('ledger-employee-select');
        eSelect.innerHTML = '<option value="">اختر موظف...</option>';
        getVisibleEmployees().forEach(e => {
            eSelect.innerHTML += `<option value="${e.id}">${e.name}</option>`;
        });
        const today = new Date().toISOString().split('T')[0];
        const firstDay = today.slice(0, 8) + '01';
        document.getElementById('ledger-date-from').value = firstDay;
        document.getElementById('ledger-date-to').value = today;
    }

    function generateLedger() {
        const empId = document.getElementById('ledger-employee-select').value;
        const from = document.getElementById('ledger-date-from').value;
        const to = document.getElementById('ledger-date-to').value;

        if (!empId) return alert('يرجى اختيار موظف');
        const emp = employees.find(e => String(e.id) === String(empId));

        let entries = [];

        // Advances
        const empAdv = advances.filter(a => String(a.employee_id) === String(empId) && a.date >= from && a.date <= to);
        empAdv.forEach(a => {
            entries.push({ date: a.date, desc: 'استلام سلفة نقدية', debit: parseFloat(a.amount), credit: 0 });
        });

        // Payrolls
        const empPr = payrolls.filter(p => p.date >= from && p.date <= to);
        empPr.forEach(p => {
            const grid = JSON.parse(p.grid || '[]');
            const row = grid.find(g => String(g.employee.id) === String(empId));
            if (row) {
                // Payroll creates a credit for the Net
                entries.push({ date: p.date, desc: `استحقاق راتب شهر ${p.month}`, debit: 0, credit: row.net });
                
                if (row.advanceDeduction > 0) {
                    entries.push({ date: p.date, desc: `سداد قسط سلفة من راتب ${p.month}`, debit: 0, credit: row.advanceDeduction });
                }
            }
        });

        // Sort entries by date
        entries.sort((a,b) => new Date(a.date) - new Date(b.date));

        const tbody = document.getElementById('hr-ledger-tbody');
        tbody.innerHTML = '';
        let balance = 0;

        entries.forEach(e => {
            balance += e.debit - e.credit; // Debit means Employee owes Company. Credit means Company owes Employee.
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${e.date}</td>
                <td>${e.desc}</td>
                <td style="color:var(--danger)">${e.debit > 0 ? e.debit.toFixed(2) : '-'}</td>
                <td style="color:var(--success)">${e.credit > 0 ? e.credit.toFixed(2) : '-'}</td>
                <td style="font-weight:bold;">${balance.toFixed(2)}</td>
            `;
            tbody.appendChild(tr);
        });

        let balanceText = balance > 0 ? `${Math.abs(balance).toFixed(2)} (عليه للشركة)` : 
                          balance < 0 ? `${Math.abs(balance).toFixed(2)} (له في الشركة)` : '0';
        document.getElementById('ledger-final-balance').innerText = balanceText;
        
        window.currentLedgerEmp = emp;
        window.currentLedgerBalance = balanceText;
        window.currentLedgerEntries = entries;
    }

    function sendLedgerWhatsApp() {
        if (!window.currentLedgerEmp) return alert('يرجى عرض الكشف أولاً');
        const phone = window.currentLedgerEmp.phone;
        if (!phone) return alert('الموظف ليس لديه رقم هاتف مسجل');

        let msg = `*مرحباً ${window.currentLedgerEmp.name}*nn`;
        msg += `إليك كشف الحساب الخاص بك:n`;
        window.currentLedgerEntries.forEach(e => {
            msg += `- ${e.date}: ${e.desc} `;
            if (e.debit > 0) msg += `(عليك: ${e.debit})n`;
            else if (e.credit > 0) msg += `(لك: ${e.credit})n`;
        });
        msg += `n*الرصيد النهائي: ${window.currentLedgerBalance}*nnمع تحيات قسم الموارد البشرية.`;

        const url = `https://wa.me/${phone.replace(/[^0-9]/g, '')}?text=${encodeURIComponent(msg)}`;
        window.open(url, '_blank');
    }

    function logout() {
        sessionStorage.removeItem('currentUser');
        window.location.href = 'index.html';
    }

    window.onload = init;

    return {
        login: init, // if called manually
        logout,
        openEmployeeModal,
        closeEmployeeModal,
        saveEmployee,
        deleteEmployee,
        openAdvanceModal,
        closeAdvanceModal,
        saveAdvance,
        deleteAdvance,
        generatePayroll,
        recalcPayrollRow,
        savePayroll,
        executePayPayroll,
        generateLedger,
        sendLedgerWhatsApp
    };
})();
