<?php
/**
 * Staff Salaries Management Page - Enhanced with Bulk Payments
 * SSCI Office Platform
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];
$pageTitle = trans('salaries') . ' - ' . config('app.name');

if (!$auth->isAuthenticated() || !$auth->canAccessPage('salaries')) {
    header('Location: ?page=login');
    exit();
}

require_once __DIR__ . '/../../layouts/header.php';

$_GET['page'] = 'salaries';
?>

<div class="animate__animated animate__fadeIn w-full mx-auto px-4 sm:px-6 lg:px-8 max-w-7xl pb-20 md:pb-8">
    <!-- Page Header -->
    <div class="mb-6 flex justify-between items-center">
        <div>
            <h1 class="text-3xl font-bold text-gray-800">
                <i class="fas fa-money-bill-wave text-green-600 mr-3"></i><?php echo trans('salaries'); ?>
            </h1>
            <p class="text-gray-600 text-sm mt-1">Manage and track staff salary payments</p>
        </div>
        <div class="flex gap-2">
            <button onclick="openPayGroupModal()" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition">
                <i class="fas fa-layer-group mr-2"></i>Pay Group
            </button>
            <button onclick="openSalaryModal()" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                <i class="fas fa-plus mr-2"></i>New Salary
            </button>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
            <input type="text" id="searchFilter" placeholder="Search staff..." class="border border-gray-300 rounded-lg px-3 py-2" onchange="loadAndFilter()">
            <select id="statusFilter" class="border border-gray-300 rounded-lg px-3 py-2" onchange="loadAndFilter()">
                <option value="">All Status</option>
                <option value="Draft">Draft</option>
                <option value="Approved">Approved</option>
                <option value="Paid">Paid</option>
            </select>
            <input type="month" id="monthFilter" class="border border-gray-300 rounded-lg px-3 py-2" onchange="loadAndFilter()">
            <select id="methodFilter" class="border border-gray-300 rounded-lg px-3 py-2" onchange="loadAndFilter()">
                <option value="">All Methods</option>
                <option value="Bank Transfer">Bank Transfer</option>
                <option value="Cash">Cash</option>
                <option value="Mobile Money">Mobile Money</option>
            </select>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow p-4 border-l-4 border-blue-500">
            <p class="text-gray-600 text-xs uppercase">Total</p>
            <p class="text-2xl font-bold" id="totalCount">0</p>
        </div>
        <div class="bg-white rounded-lg shadow p-4 border-l-4 border-green-500">
            <p class="text-gray-600 text-xs uppercase">Gross</p>
            <p class="text-2xl font-bold text-green-600" id="totalGross">0</p>
        </div>
        <div class="bg-white rounded-lg shadow p-4 border-l-4 border-orange-500">
            <p class="text-gray-600 text-xs uppercase">Deductions</p>
            <p class="text-2xl font-bold text-orange-600" id="totalDed">0</p>
        </div>
        <div class="bg-white rounded-lg shadow p-4 border-l-4 border-purple-500">
            <p class="text-gray-600 text-xs uppercase">Net</p>
            <p class="text-2xl font-bold text-purple-600" id="totalNet">0</p>
        </div>
    </div>

    <!-- Bulk Actions -->
    <div id="bulkBar" class="hidden bg-blue-50 border border-blue-200 rounded-lg p-3 mb-6 flex gap-2 items-center">
        <span id="bulkCount" class="text-sm font-semibold"></span>
        <select id="bulkStatus" class="border rounded px-3 py-1 text-sm">
            <option value="">Change Status...</option>
            <option value="Draft">Draft</option>
            <option value="Approved">Approved</option>
            <option value="Paid">Paid</option>
        </select>
        <button onclick="applyBulkStatus()" class="bg-blue-600 text-white px-3 py-1 rounded text-sm hover:bg-blue-700">Apply</button>
        <button onclick="bulkMarkPaid()" class="bg-green-600 text-white px-3 py-1 rounded text-sm hover:bg-green-700">
            <i class="fas fa-check mr-1"></i>Mark Paid
        </button>
        <button onclick="clearSelection()" class="ml-auto bg-gray-400 text-white px-3 py-1 rounded text-sm">Clear</button>
    </div>

    <!-- Table -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 border-b">
                    <tr>
                        <th class="px-4 py-3"><input type="checkbox" id="selectAll" onchange="toggleAll()" class="cursor-pointer"></th>
                        <th class="px-4 py-3 text-left text-sm font-semibold">Staff</th>
                        <th class="px-4 py-3 text-left text-sm font-semibold">Position</th>
                        <th class="px-4 py-3 text-left text-sm font-semibold">Month</th>
                        <th class="px-4 py-3 text-right text-sm font-semibold">Gross</th>
                        <th class="px-4 py-3 text-right text-sm font-semibold">Ded.</th>
                        <th class="px-4 py-3 text-right text-sm font-semibold">Net</th>
                        <th class="px-4 py-3 text-sm font-semibold">Status</th>
                        <th class="px-4 py-3 text-center text-sm font-semibold">Actions</th>
                    </tr>
                </thead>
                <tbody id="tbody" class="divide-y">
                    <tr><td colspan="9" class="px-4 py-8 text-center text-gray-500">Loading...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Salary Modal -->
<div id="salaryModal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center overflow-y-auto">
    <div class="bg-white rounded-lg w-full max-w-3xl my-8">
        <div class="sticky top-0 bg-gradient-to-r from-green-600 to-green-700 px-6 py-4 text-white flex justify-between items-center">
            <h2 id="modalTitle" class="font-bold text-lg">New Salary</h2>
            <button onclick="document.getElementById('salaryModal').classList.add('hidden')" class="text-2xl">×</button>
        </div>

        <div class="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
            <!-- Staff Selection -->
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium mb-1">Staff *</label>
                    <select id="staffSel" class="w-full border rounded-lg px-3 py-2" required onchange="onStaffSelected()">
                        <option value="">Select...</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">Month *</label>
                    <input type="month" id="monthSel" class="w-full border rounded-lg px-3 py-2" required>
                </div>
            </div>

            <!-- Staff Info Display -->
            <div id="staffInfoDisplay" class="hidden bg-blue-50 border border-blue-200 rounded-lg p-3">
                <div class="grid grid-cols-2 gap-4 text-sm">
                    <div>
                        <p class="text-gray-600">Position</p>
                        <p class="font-semibold" id="staffPosition">-</p>
                    </div>
                    <div>
                        <p class="text-gray-600">Zone</p>
                        <p class="font-semibold" id="staffZone">-</p>
                    </div>
                </div>
            </div>

            <!-- Remunerations Editor -->
            <div class="border rounded-lg p-4">
                <div class="flex justify-between items-center mb-3">
                    <h3 class="font-semibold text-gray-700">Remunerations (Income Items)</h3>
                    <button type="button" onclick="addRemunerationRow()" class="bg-blue-600 text-white px-3 py-1 rounded text-sm hover:bg-blue-700">
                        <i class="fas fa-plus mr-1"></i>Add Item
                    </button>
                </div>
                <div id="remunerationsTable" class="space-y-2 max-h-48 overflow-y-auto">
                    <div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2">
                        <div class="col-span-7">Item Name</div>
                        <div class="col-span-4">Amount</div>
                        <div class="col-span-1"></div>
                    </div>
                    <!-- Rows will be added here dynamically -->
                </div>
            </div>

            <!-- Deductions Editor -->
            <div class="border rounded-lg p-4">
                <div class="flex justify-between items-center mb-3">
                    <h3 class="font-semibold text-gray-700">Deductions (Expense Items)</h3>
                    <button type="button" onclick="addDeductionRow()" class="bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700">
                        <i class="fas fa-plus mr-1"></i>Add Item
                    </button>
                </div>
                <div id="deductionsTable" class="space-y-2 max-h-48 overflow-y-auto">
                    <div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2">
                        <div class="col-span-7">Item Name</div>
                        <div class="col-span-4">Amount</div>
                        <div class="col-span-1"></div>
                    </div>
                    <!-- Rows will be added here dynamically -->
                </div>
            </div>

            <!-- Gross & Net Calculations -->
            <div class="grid grid-cols-3 gap-4">
                <div class="bg-green-50 border border-green-200 rounded-lg p-3">
                    <label class="block text-sm font-medium mb-1 text-gray-700">Gross Amount</label>
                    <input type="number" id="grossSel" class="w-full border rounded-lg px-3 py-2 bg-white font-semibold text-green-600" readonly>
                </div>
                <div class="bg-red-50 border border-red-200 rounded-lg p-3">
                    <label class="block text-sm font-medium mb-1 text-gray-700">Total Deductions</label>
                    <input type="number" id="totalDedSel" class="w-full border rounded-lg px-3 py-2 bg-white font-semibold text-red-600" readonly>
                </div>
                <div class="bg-purple-50 border border-purple-200 rounded-lg p-3">
                    <label class="block text-sm font-medium mb-1 text-gray-700">Net Amount</label>
                    <input type="number" id="netSel" class="w-full border rounded-lg px-3 py-2 bg-white font-semibold text-purple-600" readonly>
                </div>
            </div>

            <!-- Amount in Words -->
            <div class="grid grid-cols-2 gap-4">
                <div class="bg-green-50 border border-green-200 rounded-lg p-3">
                    <p class="text-xs text-gray-600 mb-1">Gross in Words</p>
                    <p class="font-semibold text-sm text-green-700" id="grossInWords">Zero</p>
                </div>
                <div class="bg-purple-50 border border-purple-200 rounded-lg p-3">
                    <p class="text-xs text-gray-600 mb-1">Net in Words</p>
                    <p class="font-semibold text-sm text-purple-700" id="netInWords">Zero</p>
                </div>
            </div>

            <!-- Payment Details -->
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium mb-1">Status</label>
                    <select id="statuSel" class="w-full border rounded-lg px-3 py-2">
                        <option>Draft</option>
                        <option>Approved</option>
                        <option>Paid</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">Payment Method</label>
                    <select id="methodSel" class="w-full border rounded-lg px-3 py-2">
                        <option>Bank Transfer</option>
                        <option>Cash</option>
                        <option>Mobile Money</option>
                    </select>
                </div>
            </div>

            <textarea id="notesSel" placeholder="Notes..." class="w-full border rounded-lg px-3 py-2" rows="2"></textarea>
        </div>

        <div class="border-t px-6 py-4 flex gap-2 justify-end">
            <button onclick="saveSalary()" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700">Save Salary</button>
            <button onclick="document.getElementById('salaryModal').classList.add('hidden')" class="border px-4 py-2 rounded">Cancel</button>
        </div>
    </div>
</div>

<!-- Pay Group Modal -->
<div id="payGroupModal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center overflow-y-auto">
    <div class="bg-white rounded-lg w-full max-w-4xl my-8">
        <div class="sticky top-0 bg-gradient-to-r from-purple-600 to-purple-700 px-6 py-4 text-white flex justify-between items-center">
            <h2 class="font-bold text-lg">Create Pay Group - Pay Multiple Staff</h2>
            <button onclick="document.getElementById('payGroupModal').classList.add('hidden')" class="text-2xl">×</button>
        </div>

        <div class="p-6 space-y-6 max-h-[70vh] overflow-y-auto">
            <!-- Salary Month Selection -->
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium mb-1">Salary Month *</label>
                    <input type="month" id="pgMonth" class="w-full border rounded-lg px-3 py-2" required onchange="loadStaffForMonth()">
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">Status</label>
                    <select id="pgStatus" class="w-full border rounded-lg px-3 py-2">
                        <option value="Incomplete">Incomplete</option>
                        <option value="Complete">Complete</option>
                    </select>
                </div>
            </div>

            <!-- Staff Selection -->
            <div class="border rounded-lg p-4 bg-gray-50">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="font-semibold text-gray-700">Select Staff Members</h3>
                    <label class="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" id="pgSelectAll" onchange="togglePGStaff()" class="rounded">
                        <span class="text-sm">Select All</span>
                    </label>
                </div>
                <div id="pgStaffList" class="space-y-2 max-h-48 overflow-y-auto">
                    <p class="text-gray-500 text-sm">Select a month to see staff</p>
                </div>
            </div>

            <!-- Bonus Section - Repeating Items -->
            <div class="border rounded-lg p-4">
                <div class="flex justify-between items-center mb-3">
                    <h3 class="font-semibold text-gray-700">Global Bonuses (applied to all selected staff)</h3>
                    <button type="button" onclick="addPayGroupBonusRow()" class="bg-green-600 text-white px-3 py-1 rounded text-sm hover:bg-green-700">
                        <i class="fas fa-plus mr-1"></i>Add Bonus Item
                    </button>
                </div>
                <div id="pgBonusTable" class="space-y-2 max-h-40 overflow-y-auto border rounded-lg p-3 bg-gray-50">
                    <div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2">
                        <div class="col-span-4">Bonus Description</div>
                        <div class="col-span-3">Type</div>
                        <div class="col-span-4">Amount</div>
                        <div class="col-span-1"></div>
                    </div>
                    <!-- Rows will be added here dynamically -->
                </div>
            </div>

            <!-- Deductions Section - Repeating Items -->
            <div class="border rounded-lg p-4">
                <div class="flex justify-between items-center mb-3">
                    <h3 class="font-semibold text-gray-700">Global Deductions (applied to all selected staff)</h3>
                    <button type="button" onclick="addPayGroupDeductionRow()" class="bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700">
                        <i class="fas fa-plus mr-1"></i>Add Deduction Item
                    </button>
                </div>
                <div id="pgDeductionsTable" class="space-y-2 max-h-40 overflow-y-auto border rounded-lg p-3 bg-gray-50">
                    <div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2">
                        <div class="col-span-4">Deduction Description</div>
                        <div class="col-span-3">Type</div>
                        <div class="col-span-4">Amount</div>
                        <div class="col-span-1"></div>
                    </div>
                    <!-- Rows will be added here dynamically -->
                </div>
            </div>

            <!-- Partial Payment Section -->
            <div class="border rounded-lg p-4 bg-blue-50">
                <label class="flex items-center gap-2 cursor-pointer mb-3">
                    <input type="checkbox" id="pgPartialEnabled" onchange="togglePartialPayment()" class="rounded">
                    <span class="font-semibold text-gray-700">Partial Payment (Pay Part of Total)</span>
                </label>
                <div id="pgPartialSection" class="hidden grid grid-cols-3 gap-4">
                    <div>
                        <label class="block text-sm font-medium mb-1">Payment Type</label>
                        <select id="pgPartialType" class="w-full border rounded-lg px-3 py-2">
                            <option value="Amount">Fixed Amount</option>
                            <option value="Percentage">Percentage %</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-1">Amount/Percentage</label>
                        <input type="number" id="pgPartialValue" class="w-full border rounded-lg px-3 py-2" step="0.01" placeholder="0">
                    </div>
                    <div class="flex items-end">
                        <div class="w-full">
                            <label class="text-xs text-gray-500">Will Pay</label>
                            <p id="pgPartialPreview" class="text-sm font-semibold text-blue-600">0 XAF</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Summary -->
            <div class="bg-gradient-to-r from-purple-100 to-blue-100 rounded-lg p-4">
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div>
                        <p class="text-xs text-gray-600">Selected Staff</p>
                        <p class="text-2xl font-bold text-gray-800" id="pgStaffCount">0</p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-600">Total Gross</p>
                        <p class="text-2xl font-bold text-green-600" id="pgTotalGross">0 XAF</p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-600">Bonus+Ded</p>
                        <p class="text-2xl font-bold text-orange-600" id="pgAdjustment">0 XAF</p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-600">To Pay</p>
                        <p class="text-2xl font-bold text-purple-600" id="pgToPay">0 XAF</p>
                    </div>
                </div>
            </div>

            <textarea id="pgNotes" placeholder="Notes..." class="w-full border rounded-lg px-3 py-2" rows="2"></textarea>
        </div>

        <div class="border-t px-6 py-4 flex gap-2 justify-end">
            <button onclick="createPayGroup()" class="bg-purple-600 text-white px-4 py-2 rounded hover:bg-purple-700">Create Pay Group</button>
            <button onclick="document.getElementById('payGroupModal').classList.add('hidden')" class="border px-4 py-2 rounded">Cancel</button>
        </div>
    </div>
</div>

<script>
let allSalaries = [];
let allStaff = [];
let page = 0;
const pageSize = 20;
let selectedIds = [];
let remunerationRows = [];
let deductionRows = [];
let currentStaffData = null;
let editId = null;

async function loadAndFilter() {
    const res = await fetch('?page=api&endpoint=salaries/list');
    const data = await res.json();
    if (data.salaries) {
        allSalaries = data.salaries;
        filter();
    }
}

function filter() {
    const search = document.getElementById('searchFilter').value.toLowerCase();
    const status = document.getElementById('statusFilter').value;
    const month = document.getElementById('monthFilter').value;
    const method = document.getElementById('methodFilter').value;

    let filtered = allSalaries.filter(s => {
        if (search && !s.staff_name.toLowerCase().includes(search)) return false;
        if (status && s.status !== status) return false;
        if (month && s.salary_month !== month) return false;
        if (method && s.payment_method !== method) return false;
        return true;
    });

    // Update summary
    const gross = filtered.reduce((a, s) => a + parseFloat(s.gross_amount || 0), 0);
    const ded = filtered.reduce((a, s) => a + parseFloat(s.total_deductions || 0), 0);
    const net = filtered.reduce((a, s) => a + parseFloat(s.net_amount || 0), 0);

    document.getElementById('totalCount').textContent = filtered.length;
    document.getElementById('totalGross').textContent = formatNum(gross) + ' XAF';
    document.getElementById('totalDed').textContent = formatNum(ded) + ' XAF';
    document.getElementById('totalNet').textContent = formatNum(net) + ' XAF';

    // Paginate
    page = 0;
    displayPage(filtered);
}

function displayPage(filtered) {
    const start = page * pageSize;
    const rows = filtered.slice(start, start + pageSize);

    const tbody = document.getElementById('tbody');
    tbody.innerHTML = rows.map((s, i) => `
        <tr class="hover:bg-gray-50">
            <td class="px-4 py-3"><input type="checkbox" class="salary-cb" value="${s.id}" onchange="updateBulk()"></td>
            <td class="px-4 py-3 font-semibold">${s.staff_name}</td>
            <td class="px-4 py-3">${s.position || '-'}</td>
            <td class="px-4 py-3">${s.salary_month}</td>
            <td class="px-4 py-3 text-right">${formatNum(s.gross_amount)}</td>
            <td class="px-4 py-3 text-right">${formatNum(s.total_deductions)}</td>
            <td class="px-4 py-3 text-right font-semibold">${formatNum(s.net_amount)}</td>
            <td class="px-4 py-3"><span class="px-2 py-1 text-xs font-semibold rounded ${s.status === 'Paid' ? 'bg-green-100 text-green-800' : s.status === 'Approved' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100'}">${s.status}</span></td>
            <td class="px-4 py-3 text-center space-x-2">
                <button onclick="editSalary(${s.id})" class="text-blue-600 hover:text-blue-800"><i class="fas fa-edit"></i></button>
                <button onclick="downloadPayslip(${s.id})" class="text-purple-600 hover:text-purple-800"><i class="fas fa-download"></i></button>
                <button onclick="delSalary(${s.id})" class="text-red-600 hover:text-red-800"><i class="fas fa-trash"></i></button>
            </td>
        </tr>
    `).join('');
}

function openSalaryModal() {
    document.getElementById('modalTitle').textContent = 'New Salary';
    document.getElementById('staffSel').value = '';
    document.getElementById('monthSel').value = new Date().toISOString().slice(0, 7);
    document.getElementById('staffInfoDisplay').classList.add('hidden');
    remunerationRows = [];
    deductionRows = [];
    clearRemunerations();
    clearDeductions();
    addRemunerationRow();
    addDeductionRow();
    calcSalaryNet();
    document.getElementById('salaryModal').classList.remove('hidden');
    editId = null;
}

async function onStaffSelected() {
    const staffId = document.getElementById('staffSel').value;
    if (!staffId) {
        document.getElementById('staffInfoDisplay').classList.add('hidden');
        return;
    }

    const staff = allStaff.find(s => s.id == staffId);
    if (staff) {
        currentStaffData = staff;
        document.getElementById('staffPosition').textContent = staff.position || '-';
        document.getElementById('staffZone').textContent = staff.zone || '-';
        document.getElementById('staffInfoDisplay').classList.remove('hidden');

        // Load remunerations from staff
        remunerationRows = [];
        clearRemunerations();
        
        if (staff.remunerations) {
            try {
                const remuns = typeof staff.remunerations === 'string' ? JSON.parse(staff.remunerations) : staff.remunerations;
                if (Array.isArray(remuns)) {
                    remuns.forEach(r => {
                        addRemunerationRow(r.item || '', r.amount || 0);
                    });
                } else {
                    addRemunerationRow('', 0);
                }
            } catch (e) {
                addRemunerationRow('', 0);
            }
        } else {
            addRemunerationRow('', 0);
        }
        calcSalaryNet();
    }
}

function clearRemunerations() {
    document.getElementById('remunerationsTable').innerHTML = `
        <div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2">
            <div class="col-span-7">Item Name</div>
            <div class="col-span-4">Amount</div>
            <div class="col-span-1"></div>
        </div>
    `;
}

function clearDeductions() {
    document.getElementById('deductionsTable').innerHTML = `
        <div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2">
            <div class="col-span-7">Item Name</div>
            <div class="col-span-4">Amount</div>
            <div class="col-span-1"></div>
        </div>
    `;
}

function addRemunerationRow(itemName = '', amount = 0) {
    const container = document.getElementById('remunerationsTable');
    const rowId = 'remun-' + Date.now() + Math.random();
    
    const row = document.createElement('div');
    row.id = rowId;
    row.className = 'grid grid-cols-12 gap-2';
    row.innerHTML = `
        <input type="text" placeholder="e.g., Basic Salary" value="${itemName}" class="col-span-7 border rounded px-2 py-1 text-sm remun-name" onchange="calcSalaryNet()">
        <input type="number" placeholder="0" value="${amount}" step="0.01" class="col-span-4 border rounded px-2 py-1 text-sm remun-amount" onchange="calcSalaryNet()">
        <button type="button" onclick="removeRemunerationRow('${rowId}')" class="col-span-1 text-red-600 hover:text-red-800 text-center">
            <i class="fas fa-trash-alt text-sm"></i>
        </button>
    `;
    
    container.appendChild(row);
    remunerationRows.push(rowId);
}

function removeRemunerationRow(rowId) {
    const row = document.getElementById(rowId);
    if (row) {
        row.remove();
        remunerationRows = remunerationRows.filter(id => id !== rowId);
        calcSalaryNet();
    }
}

function addDeductionRow(itemName = '', amount = 0) {
    const container = document.getElementById('deductionsTable');
    const rowId = 'ded-' + Date.now() + Math.random();
    
    const row = document.createElement('div');
    row.id = rowId;
    row.className = 'grid grid-cols-12 gap-2';
    row.innerHTML = `
        <input type="text" placeholder="e.g., Tax, Insurance" value="${itemName}" class="col-span-7 border rounded px-2 py-1 text-sm ded-name" onchange="calcSalaryNet()">
        <input type="number" placeholder="0" value="${amount}" step="0.01" class="col-span-4 border rounded px-2 py-1 text-sm ded-amount" onchange="calcSalaryNet()">
        <button type="button" onclick="removeDeductionRow('${rowId}')" class="col-span-1 text-red-600 hover:text-red-800 text-center">
            <i class="fas fa-trash-alt text-sm"></i>
        </button>
    `;
    
    container.appendChild(row);
    deductionRows.push(rowId);
}

function removeDeductionRow(rowId) {
    const row = document.getElementById(rowId);
    if (row) {
        row.remove();
        deductionRows = deductionRows.filter(id => id !== rowId);
        calcSalaryNet();
    }
}

function calcSalaryNet() {
    // Calculate gross from remunerations
    let gross = 0;
    document.querySelectorAll('.remun-amount').forEach(input => {
        gross += parseFloat(input.value || 0);
    });

    // Calculate total deductions from deductions table
    let totalDed = 0;
    document.querySelectorAll('.ded-amount').forEach(input => {
        totalDed += parseFloat(input.value || 0);
    });

    const net = Math.max(0, gross - totalDed);

    document.getElementById('grossSel').value = gross.toFixed(2);
    document.getElementById('totalDedSel').value = totalDed.toFixed(2);
    document.getElementById('netSel').value = net.toFixed(2);
    
    // Update amount in words
    document.getElementById('grossInWords').textContent = numberToWords(Math.round(gross)) + ' XAF';
    document.getElementById('netInWords').textContent = numberToWords(Math.round(net)) + ' XAF';
}

function saveSalary() {
    const staffId = document.getElementById('staffSel').value;
    const month = document.getElementById('monthSel').value;

    console.log('DEBUG: saveSalary() called');
    console.log('DEBUG: staffId =', staffId);
    console.log('DEBUG: month =', month);
    console.log('DEBUG: staffSel element value =', document.getElementById('staffSel').value);
    console.log('DEBUG: all staff list =', allStaff);

    if (!staffId || !month) {
        Swal.fire('Error', 'Staff and month are required', 'error');
        return;
    }

    // Collect remunerations
    const remunerations = [];
    document.querySelectorAll('#remunerationsTable > div:not(:first-child)').forEach(row => {
        const name = row.querySelector('.remun-name').value;
        const amount = parseFloat(row.querySelector('.remun-amount').value || 0);
        if (name && amount > 0) {
            remunerations.push({ item: name, amount });
        }
    });

    if (remunerations.length === 0) {
        Swal.fire('Error', 'Add at least one remuneration item', 'error');
        return;
    }

    // Collect deductions
    const deductions = [];
    document.querySelectorAll('#deductionsTable > div:not(:first-child)').forEach(row => {
        const name = row.querySelector('.ded-name').value;
        const amount = parseFloat(row.querySelector('.ded-amount').value || 0);
        if (name && amount > 0) {
            deductions.push({ item: name, amount });
        }
    });

    const totalDeductions = parseFloat(document.getElementById('totalDedSel').value || 0);

    const data = {
        staff_id: staffId,
        salary_month: month,
        remunerations: remunerations,
        deductions: deductions,
        total_deductions: totalDeductions,
        gross_amount: parseFloat(document.getElementById('grossSel').value),
        net_amount: parseFloat(document.getElementById('netSel').value),
        status: document.getElementById('statuSel').value,
        payment_method: document.getElementById('methodSel').value,
        notes: document.getElementById('notesSel').value
    };

    const endpoint = editId ? 'salaries/update' : 'salaries/create';
    const method = editId ? 'PUT' : 'POST';
    if (editId) data.id = editId;

    fetch(`?page=api&endpoint=${endpoint}`, {
        method: method,
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            Swal.fire('Success', 'Salary saved', 'success');
            document.getElementById('salaryModal').classList.add('hidden');
            loadAndFilter();
        } else {
            Swal.fire('Error', res.message || 'Failed to save', 'error');
        }
    })
    .catch(e => {
        console.error(e);
        Swal.fire('Error', 'Failed to save salary', 'error');
    });
}

function editSalary(id) {
    const s = allSalaries.find(x => x.id == id);
    if (!s) return;

    editId = id;
    document.getElementById('modalTitle').textContent = 'Edit Salary';
    document.getElementById('staffSel').value = s.staff_id;
    document.getElementById('monthSel').value = s.salary_month;
    document.getElementById('statuSel').value = s.status;
    document.getElementById('methodSel').value = s.payment_method;
    document.getElementById('notesSel').value = s.notes || '';

    // Load remunerations
    remunerationRows = [];
    clearRemunerations();
    
    if (s.remunerations) {
        try {
            const remuns = typeof s.remunerations === 'string' ? JSON.parse(s.remunerations) : s.remunerations;
            if (Array.isArray(remuns)) {
                remuns.forEach(r => {
                    addRemunerationRow(r.item || '', r.amount || 0);
                });
            } else {
                addRemunerationRow('', 0);
            }
        } catch (e) {
            addRemunerationRow('', 0);
        }
    }

    // Load deductions
    deductionRows = [];
    clearDeductions();
    
    if (s.deductions) {
        try {
            const deds = typeof s.deductions === 'string' ? JSON.parse(s.deductions) : s.deductions;
            if (Array.isArray(deds)) {
                deds.forEach(d => {
                    addDeductionRow(d.item || '', d.amount || 0);
                });
            } else {
                addDeductionRow('', 0);
            }
        } catch (e) {
            addDeductionRow('', 0);
        }
    }

    // Get staff data for display
    onStaffSelected();
    calcSalaryNet();
    document.getElementById('salaryModal').classList.remove('hidden');
}

function delSalary(id) {
    Swal.fire({
        title: 'Delete?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Delete'
    }).then(r => {
        if (r.isConfirmed) {
            fetch(`?page=api&endpoint=salaries/delete&id=${id}`, {method: 'DELETE'})
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    Swal.fire('Deleted', '', 'success');
                    loadAndFilter();
                }
            });
        }
    });
}

function downloadPayslip(id) {
    window.location.href = `?page=api&endpoint=salaries/payslip&id=${id}`;
}

function formatNum(n) {
    return Math.round(n).toLocaleString();
}

function toggleAll() {
    const all = document.getElementById('selectAll').checked;
    document.querySelectorAll('.salary-cb').forEach(cb => cb.checked = all);
    updateBulk();
}

function updateBulk() {
    selectedIds = Array.from(document.querySelectorAll('.salary-cb:checked')).map(x => x.value);
    const bar = document.getElementById('bulkBar');
    if (selectedIds.length > 0) {
        bar.classList.remove('hidden');
        document.getElementById('bulkCount').textContent = selectedIds.length + ' selected';
    } else {
        bar.classList.add('hidden');
    }
}

function applyBulkStatus() {
    const status = document.getElementById('bulkStatus').value;
    if (!status) return;

    fetch('?page=api&endpoint=salaries/bulk-update', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ids: selectedIds, status: status})
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            Swal.fire('Success', 'Updated', 'success');
            clearSelection();
            loadAndFilter();
        }
    });
}

function bulkMarkPaid() {
    fetch('?page=api&endpoint=salaries/bulk-pay', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ids: selectedIds})
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            Swal.fire('Success', 'Marked paid', 'success');
            clearSelection();
            loadAndFilter();
        }
    });
}

function clearSelection() {
    document.querySelectorAll('.salary-cb').forEach(cb => cb.checked = false);
    document.getElementById('selectAll').checked = false;
    updateBulk();
}

// ===== NUMBER TO WORDS CONVERSION =====
function numberToWords(num) {
    const ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
    const teens = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
    const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
    const scales = ['', 'Thousand', 'Million', 'Billion'];

    if (num === 0) return 'Zero';

    const convert = (n) => {
        if (n === 0) return '';
        if (n < 10) return ones[n];
        if (n < 20) return teens[n - 10];
        if (n < 100) return tens[Math.floor(n / 10)] + (n % 10 ? ' ' + ones[n % 10] : '');
        return ones[Math.floor(n / 100)] + ' Hundred' + (n % 100 ? ' ' + convert(n % 100) : '');
    };

    let parts = [];
    let scaleIndex = 0;
    while (num > 0) {
        if (num % 1000 !== 0) {
            parts.unshift(convert(num % 1000) + (scaleIndex > 0 ? ' ' + scales[scaleIndex] : ''));
        }
        num = Math.floor(num / 1000);
        scaleIndex++;
    }
    return parts.join(' ');
}

// Load staff data on page load
async function loadStaffList() {
    try {
        const res = await fetch('?page=api&endpoint=staff/list');
        const data = await res.json();
        console.log('Staff API Response:', data);
        
        if (data.data || data.staff) {
            allStaff = data.data || data.staff;
            console.log('Loaded staff:', allStaff);
            console.log('DEBUG: Staff IDs available:', allStaff.map(s => ({id: s.id, user_id: s.user_id, name: s.employee_name || s.name})));
            
            const sel = document.getElementById('staffSel');
            sel.innerHTML = '<option value="">Select Staff...</option>';
            allStaff.forEach(s => {
                const opt = document.createElement('option');
                // IMPORTANT: Use user_id because staff_salaries.staff_id references users.id
                opt.value = s.user_id;
                // Use employee_name if available, otherwise name
                const staffName = s.employee_name || s.name || 'Unknown';
                opt.textContent = staffName + ' (' + (s.position || 'N/A') + ')';
                opt.dataset.staffTableId = s.id; // Store staff.id as data attribute for reference
                sel.appendChild(opt);
                console.log('Added option:', staffName, 'user_id=', s.user_id, 'staff.id=', s.id);
            });
            console.log('Staff selector populated with', allStaff.length, 'items');
        } else {
            console.error('No data in response');
        }
    } catch (e) {
        console.error('Failed to load staff:', e);
    }
}

loadStaffList();
loadAndFilter();

// ===== PAY GROUP FUNCTIONS =====
let pgBonusRows = [];
let pgDeductionRows = [];

async function openPayGroupModal() {
    document.getElementById('payGroupModal').classList.remove('hidden');
    const today = new Date().toISOString().slice(0, 7);
    document.getElementById('pgMonth').value = today;
    resetPayGroupForm();
    // Load staff for current month
    await loadStaffForMonth();
}

async function loadStaffForMonth() {
    const month = document.getElementById('pgMonth').value;
    if (!month) {
        document.getElementById('pgStaffList').innerHTML = '<p class="text-gray-500 text-sm">Select a month to see staff</p>';
        return;
    }

    const container = document.getElementById('pgStaffList');
    if (!allStaff || allStaff.length === 0) {
        container.innerHTML = '<p class="text-gray-500 text-sm">No staff available</p>';
        return;
    }

    // Show all active staff (not filtered by month - can create new salaries)
    container.innerHTML = allStaff.map(s => `
        <label class="flex items-center gap-3 p-2 border rounded cursor-pointer hover:bg-white transition pg-staff-item">
            <input type="checkbox" class="pg-staff-cb" value="${s.id}" data-gross="${s.total_monthly_pay || 0}" onchange="updatePayGroupSummary()">
            <div class="flex-1">
                <p class="font-medium text-sm">${s.employee_name || s.name || 'Unknown'}</p>
                <p class="text-xs text-gray-500">${s.position || 'N/A'} - ${s.zone || ''}</p>
            </div>
            <p class="text-sm font-semibold text-gray-700">${formatNum(s.total_monthly_pay || 0)} XAF</p>
        </label>
    `).join('');
}

function togglePGStaff() {
    const all = document.getElementById('pgSelectAll').checked;
    document.querySelectorAll('.pg-staff-cb').forEach(cb => cb.checked = all);
    updatePayGroupSummary();
}

function updatePayGroupSummary() {
    const selected = Array.from(document.querySelectorAll('.pg-staff-cb:checked'));
    const staffCount = selected.length;
    const totalGross = selected.reduce((sum, cb) => sum + parseFloat(cb.dataset.gross || 0), 0);

    // Calculate total bonus from rows (accounting for Fixed vs Percentage type)
    const totalBonus = pgBonusRows.reduce((sum, row) => {
        const amount = parseFloat(row.amount) || 0;
        if (amount === 0) return sum;
        
        if (row.type === 'Fixed') {
            return sum + (amount * staffCount);  // Multiply fixed amount by number of staff
        } else {
            return sum + (totalGross * amount / 100);  // Percentage of total gross
        }
    }, 0);

    // Calculate total deductions from rows (accounting for Fixed vs Percentage type)
    const totalDed = pgDeductionRows.reduce((sum, row) => {
        const amount = parseFloat(row.amount) || 0;
        if (amount === 0) return sum;
        
        if (row.type === 'Fixed') {
            return sum + (amount * staffCount);  // Multiply fixed amount by number of staff
        } else {
            return sum + (totalGross * amount / 100);  // Percentage of total gross
        }
    }, 0);

    let toPay = totalGross + totalBonus - totalDed;

    // Apply partial payment
    if (document.getElementById('pgPartialEnabled').checked) {
        const partialType = document.getElementById('pgPartialType').value;
        const partialValue = parseFloat(document.getElementById('pgPartialValue').value || 0);
        if (partialValue > 0) {
            toPay = partialType === 'Percentage' ? (toPay * partialValue / 100) : partialValue;
        }
    }

    document.getElementById('pgStaffCount').textContent = staffCount;
    document.getElementById('pgTotalGross').textContent = formatNum(totalGross) + ' XAF';
    document.getElementById('pgAdjustment').textContent = formatNum(totalBonus - totalDed) + ' XAF';
    document.getElementById('pgToPay').textContent = formatNum(toPay) + ' XAF';
}

function togglePartialPayment() {
    const enabled = document.getElementById('pgPartialEnabled').checked;
    document.getElementById('pgPartialSection').classList.toggle('hidden', !enabled);
    updatePayGroupSummary();
}

function resetPayGroupForm() {
    document.getElementById('pgSelectAll').checked = false;
    document.getElementById('pgStatus').value = 'Incomplete';
    document.getElementById('pgNotes').value = '';
    document.getElementById('pgPartialEnabled').checked = false;
    document.getElementById('pgPartialType').value = 'Amount';
    document.getElementById('pgPartialValue').value = '';
    document.getElementById('pgPartialSection').classList.add('hidden');
    pgBonusRows = [];
    pgDeductionRows = [];
    clearPayGroupBonuses();
    clearPayGroupDeductions();
    updatePayGroupSummary();
}

// Pay Group Bonus Functions
function addPayGroupBonusRow(description, amount, type) {
    const rowId = Date.now() + Math.random();
    const row = {
        id: rowId,
        description: description || '',
        amount: amount || 0,
        type: type || 'Fixed'
    };
    pgBonusRows.push(row);
    renderPayGroupBonusTable();
    updatePayGroupSummary();
}

function removePayGroupBonusRow(rowId) {
    pgBonusRows = pgBonusRows.filter(r => r.id !== rowId);
    renderPayGroupBonusTable();
    updatePayGroupSummary();
}

function renderPayGroupBonusTable() {
    const table = document.getElementById('pgBonusTable');
    if (pgBonusRows.length === 0) {
        table.innerHTML = '<div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2"><div class="col-span-4">Bonus Description</div><div class="col-span-3">Type</div><div class="col-span-4">Amount</div><div class="col-span-1"></div></div>';
        return;
    }
    
    let html = '<div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2"><div class="col-span-4">Bonus Description</div><div class="col-span-3">Type</div><div class="col-span-4">Amount</div><div class="col-span-1"></div></div>';
    pgBonusRows.forEach(row => {
        html += `
            <div class="grid grid-cols-12 gap-2 items-center pb-2 border-b">
                <input type="text" class="col-span-4 border rounded px-2 py-1 text-sm" value="${row.description}" onchange="updatePayGroupBonus(${row.id}, this.value, 'description')" placeholder="e.g., Performance Bonus">
                <select class="col-span-3 border rounded px-2 py-1 text-sm" onchange="updatePayGroupBonus(${row.id}, this.value, 'type')">
                    <option value="Fixed" ${row.type === 'Fixed' ? 'selected' : ''}>Fixed Amount</option>
                    <option value="Percentage" ${row.type === 'Percentage' ? 'selected' : ''}>Percentage (%)</option>
                </select>
                <input type="number" class="col-span-4 border rounded px-2 py-1 text-sm" value="${row.amount}" step="0.01" onchange="updatePayGroupBonus(${row.id}, this.value, 'amount')" placeholder="0">
                <button type="button" onclick="removePayGroupBonusRow(${row.id})" class="col-span-1 text-red-600 hover:text-red-800"><i class="fas fa-trash"></i></button>
            </div>
        `;
    });
    table.innerHTML = html;
}

function updatePayGroupBonus(rowId, value, field) {
    const row = pgBonusRows.find(r => r.id === rowId);
    if (row) {
        if (field === 'description') row.description = value;
        if (field === 'amount') row.amount = parseFloat(value) || 0;
        if (field === 'type') row.type = value;
        updatePayGroupSummary();
    }
}

function clearPayGroupBonuses() {
    pgBonusRows = [];
    renderPayGroupBonusTable();
}

// Pay Group Deduction Functions
function addPayGroupDeductionRow(description, amount, type) {
    const rowId = Date.now() + Math.random();
    const row = {
        id: rowId,
        description: description || '',
        amount: amount || 0,
        type: type || 'Fixed'
    };
    pgDeductionRows.push(row);
    renderPayGroupDeductionsTable();
    updatePayGroupSummary();
}

function removePayGroupDeductionRow(rowId) {
    pgDeductionRows = pgDeductionRows.filter(r => r.id !== rowId);
    renderPayGroupDeductionsTable();
    updatePayGroupSummary();
}

function renderPayGroupDeductionsTable() {
    const table = document.getElementById('pgDeductionsTable');
    if (pgDeductionRows.length === 0) {
        table.innerHTML = '<div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2"><div class="col-span-4">Deduction Description</div><div class="col-span-3">Type</div><div class="col-span-4">Amount</div><div class="col-span-1"></div></div>';
        return;
    }
    
    let html = '<div class="grid grid-cols-12 gap-2 text-sm font-semibold mb-2"><div class="col-span-4">Deduction Description</div><div class="col-span-3">Type</div><div class="col-span-4">Amount</div><div class="col-span-1"></div></div>';
    pgDeductionRows.forEach(row => {
        html += `
            <div class="grid grid-cols-12 gap-2 items-center pb-2 border-b">
                <input type="text" class="col-span-4 border rounded px-2 py-1 text-sm" value="${row.description}" onchange="updatePayGroupDeduction(${row.id}, this.value, 'description')" placeholder="e.g., Tax, Insurance">
                <select class="col-span-3 border rounded px-2 py-1 text-sm" onchange="updatePayGroupDeduction(${row.id}, this.value, 'type')">
                    <option value="Fixed" ${row.type === 'Fixed' ? 'selected' : ''}>Fixed Amount</option>
                    <option value="Percentage" ${row.type === 'Percentage' ? 'selected' : ''}>Percentage (%)</option>
                </select>
                <input type="number" class="col-span-4 border rounded px-2 py-1 text-sm" value="${row.amount}" step="0.01" onchange="updatePayGroupDeduction(${row.id}, this.value, 'amount')" placeholder="0">
                <button type="button" onclick="removePayGroupDeductionRow(${row.id})" class="col-span-1 text-red-600 hover:text-red-800"><i class="fas fa-trash"></i></button>
            </div>
        `;
    });
    table.innerHTML = html;
}

function updatePayGroupDeduction(rowId, value, field) {
    const row = pgDeductionRows.find(r => r.id === rowId);
    if (row) {
        if (field === 'description') row.description = value;
        if (field === 'amount') row.amount = parseFloat(value) || 0;
        if (field === 'type') row.type = value;
        updatePayGroupSummary();
    }
}

function clearPayGroupDeductions() {
    pgDeductionRows = [];
    renderPayGroupDeductionsTable();
}

async function createPayGroup() {
    const month = document.getElementById('pgMonth').value;
    const selected = Array.from(document.querySelectorAll('.pg-staff-cb:checked'));
    
    if (!month) {
        Swal.fire('Error', 'Please select a salary month', 'error');
        return;
    }
    
    if (selected.length === 0) {
        Swal.fire('Error', 'Please select at least one staff member', 'error');
        return;
    }

    const selectedIds = selected.map(cb => cb.value);
    
    // Collect bonus items
    const bonuses = pgBonusRows.map(r => ({
        description: r.description,
        amount: parseFloat(r.amount) || 0,
        type: r.type
    })).filter(b => b.amount > 0);

    // Collect deduction items
    const deductions = pgDeductionRows.map(r => ({
        description: r.description,
        amount: parseFloat(r.amount) || 0,
        type: r.type
    })).filter(d => d.amount > 0);
    
    let partialType = null;
    let partialValue = null;
    if (document.getElementById('pgPartialEnabled').checked) {
        partialType = document.getElementById('pgPartialType').value;
        partialValue = parseFloat(document.getElementById('pgPartialValue').value || 0);
    }

    const data = {
        salary_month: month,
        staff_ids: selectedIds,
        bonuses: bonuses,
        deductions: deductions,
        partial_type: partialType,
        partial_value: partialValue,
        status: document.getElementById('pgStatus').value,
        notes: document.getElementById('pgNotes').value
    };

    try {
        const res = await fetch('?page=api&endpoint=salaries/bulk-pay', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });

        const result = await res.json();
        if (result.success) {
            Swal.fire('Success', `Pay group created! ${selected.length} salaries updated`, 'success');
            document.getElementById('payGroupModal').classList.add('hidden');
            loadAndFilter();
        } else {
            Swal.fire('Error', result.message || 'Failed to create pay group', 'error');
        }
    } catch (e) {
        console.error(e);
        Swal.fire('Error', 'Failed to create pay group', 'error');
    }
}
</script>

<?php require_once __DIR__ . '/../../layouts/footer.php'; ?>

