<?php
session_start();
date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/auth_init.php';

if (!$isAdmin) {
    $_SESSION['flash_error'] = "You don't have permission to edit employee payroll setup.";
    header("Location: dashboard.php");
    exit;
}

// Nothing below writes to the session, so release the lock now instead of
// holding it for the rest of this page's queries/rendering.
session_write_close();

$initialEmployeeId = isset($_GET['employee_id']) ? (int) $_GET['employee_id'] : 0;

$pageTitle = 'Employee Payroll Setup';
$pageSubtitle = 'Payroll Module';
require __DIR__ . '/includes/layout_header.php';
?>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">Find Employee</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-3">Search by name, employee number, or designation.</p>
    <div class="relative">
        <input type="text" id="employeeSearch" autocomplete="off" placeholder="Start typing a name..."
               class="w-full text-sm border border-slate-200 bg-slate-50 rounded-lg px-3 py-2.5">
        <div id="searchResults" class="hidden absolute z-20 mt-1 w-full bg-white border border-slate-200 rounded-lg shadow-lg max-h-72 overflow-y-auto"></div>
    </div>
    <div id="selectedEmployeeBar" class="hidden mt-3 flex items-center gap-3 bg-indigo-50 border border-indigo-100 rounded-lg px-3 py-2">
        <div class="w-8 h-8 rounded-lg bg-indigo-100 border border-indigo-200 text-indigo-700 flex items-center justify-center font-black text-xs" id="selectedAvatar"></div>
        <div class="flex-1">
            <p class="text-sm font-bold text-slate-900" id="selectedName"></p>
            <p class="text-[10px] text-slate-500 font-semibold" id="selectedMeta"></p>
        </div>
        <button onclick="clearSelection()" class="text-xs font-bold text-slate-500 hover:text-rose-600 active:scale-95 transition">Change</button>
    </div>
</div>

<div id="loadingState" class="hidden text-center py-8 text-xs text-slate-400 font-semibold">Loading employee payroll data...</div>

<div id="employeePanels" class="hidden space-y-4">

    <div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
        <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">Annual Gross Salary</h3>
        <p class="text-[11px] text-slate-500 font-semibold mb-4">
            Enter this once and any component set up as a "% of Gross Salary" (in <a href="components.php" class="text-indigo-600 underline">Pay Components</a>) auto-calculates below —
            e.g. Basic Salary at 40%, Housing at 30%, Transport at 15%. You can still fine-tune any individual amount afterward.
        </p>
        <form id="grossForm" onsubmit="return saveGrossSalary(event)" class="flex flex-col sm:flex-row gap-3 items-end">
            <div class="flex-1">
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Annual Gross Salary (NGN)</label>
                <input type="number" step="0.01" id="annualGrossSalary" name="annual_gross_salary" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
            </div>
            <button type="submit" id="btnSaveGross" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-black uppercase tracking-wider px-5 py-2.5 rounded-lg transition active:scale-95 border border-indigo-700 whitespace-nowrap">
                Save & Auto-Fill Components
            </button>
        </form>
        <p class="text-[10px] text-slate-400 font-semibold mt-3" id="grossMeta"></p>
    </div>

    <div class="bg-white border border-slate-200 rounded-xl shadow-xs overflow-hidden">
        <div class="p-4 border-b border-slate-100">
            <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight" id="componentsHeading">Pay Components</h3>
            <p class="text-[10px] text-slate-500 font-semibold mt-1">Uncheck any component to remove it for this employee only. Pension is calculated on Basic + Housing + Transport (per the Pension Reform Act). Statutory deductions (PAYE, Pension, NHF, NHIS) are managed in <a href="settings.php" class="text-indigo-600 underline">Settings</a>.</p>
        </div>
        <form id="componentsForm" onsubmit="return saveComponents(event)">
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead class="bg-slate-50 text-slate-400 uppercase text-[9px] font-black tracking-wider">
                        <tr>
                            <th class="text-left p-3">Component</th>
                            <th class="text-left p-3">Type</th>
                            <th class="text-left p-3">Amount (NGN/month)</th>
                            <th class="text-left p-3">Active for Employee</th>
                            <th class="text-left p-3">Source</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100" id="componentsTbody"></tbody>
                </table>
            </div>
            <div class="p-5 border-t border-slate-100">
                <button type="submit" id="btnSaveComponents" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-black uppercase tracking-wider px-5 py-2.5 rounded-lg transition active:scale-95 border border-indigo-700">
                    Save Changes
                </button>
            </div>
        </form>
    </div>

    <div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
        <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">Annual Rent Paid (for Tax Relief)</h3>
        <p class="text-[11px] text-slate-500 font-semibold mb-4">
            This is the amount the employee actually pays their landlord per year — ask them for it (with a receipt or tenancy agreement reference if possible) and record it here.
            It's used only to calculate PAYE rent relief (20% of this, capped at ₦500,000/year) and is separate from any Housing Allowance the company pays as salary.
        </p>
        <form id="rentForm" onsubmit="return saveRent(event)" class="grid grid-cols-1 sm:grid-cols-3 gap-4 items-end">
            <div>
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Annual Rent Paid (NGN)</label>
                <input type="number" step="0.01" name="annual_rent_paid" id="annualRentPaid" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
            </div>
            <div>
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Receipt / Tenancy Reference (optional)</label>
                <input type="text" name="rent_receipt_reference" id="rentReceiptReference" placeholder="e.g. Tenancy agreement dated..." class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
            </div>
            <button type="submit" id="btnSaveRent" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-black uppercase tracking-wider px-5 py-2.5 rounded-lg transition active:scale-95 border border-indigo-700">
                Save Rent Value
            </button>
        </form>
        <p class="text-[10px] text-slate-400 font-semibold mt-3" id="rentMeta"></p>
    </div>

</div>

<script>
const ajaxUrl = 'employee_payroll_ajax.php';
let currentEmployeeId = <?= $initialEmployeeId ?: 'null'; ?>;
let searchDebounce = null;

function escapeHtml(str) {
    const div = document.createElement('div');
    div.textContent = str ?? '';
    return div.innerHTML;
}

function toast(message, isError = false) {
    const el = document.createElement('div');
    el.className = `fixed bottom-4 right-4 z-50 px-4 py-3 rounded-lg text-xs font-semibold shadow-lg border ${isError ? 'bg-rose-50 text-rose-800 border-rose-200' : 'bg-emerald-50 text-emerald-800 border-emerald-200'}`;
    el.textContent = message;
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 4000);
}

document.getElementById('employeeSearch').addEventListener('input', function() {
    const q = this.value.trim();
    clearTimeout(searchDebounce);
    searchDebounce = setTimeout(() => runSearch(q), 250);
});

document.getElementById('employeeSearch').addEventListener('focus', function() {
    if (this.value.trim() === '') runSearch('');
});

document.addEventListener('click', function(e) {
    if (!e.target.closest('#searchResults') && !e.target.closest('#employeeSearch')) {
        document.getElementById('searchResults').classList.add('hidden');
    }
});

async function runSearch(q) {
    const resultsEl = document.getElementById('searchResults');
    try {
        const res = await fetch(`${ajaxUrl}?action=search_employees&q=${encodeURIComponent(q)}`);
        const data = await res.json();
        const results = data.results || [];

        if (results.length === 0) {
            resultsEl.innerHTML = `<div class="p-3 text-xs text-slate-400 text-center">No matching employees.</div>`;
        } else {
            resultsEl.innerHTML = results.map(r => `
                <button type="button" onclick="selectEmployee(${r.id}, '${escapeHtml(r.name).replace(/'/g, "\\'")}', '${escapeHtml(r.employee_no)}', '${escapeHtml(r.designation || '').replace(/'/g, "\\'")}')"
                    class="w-full text-left px-3 py-2.5 hover:bg-slate-50 transition border-b border-slate-100 last:border-0 flex items-center gap-2.5">
                    <div class="w-7 h-7 rounded-lg bg-slate-100 border border-slate-200 text-slate-600 flex items-center justify-center font-black text-[10px] shrink-0">${escapeHtml(r.name || '?').charAt(0).toUpperCase()}</div>
                    <div class="min-w-0">
                        <p class="text-xs font-bold text-slate-900 truncate">${escapeHtml(r.name)} <span class="text-slate-400 font-normal">(${escapeHtml(r.employee_no)})</span></p>
                        <p class="text-[10px] text-slate-400 truncate">${escapeHtml(r.designation || 'No designation')}</p>
                    </div>
                </button>
            `).join('');
        }
        resultsEl.classList.remove('hidden');
    } catch (e) {
        resultsEl.innerHTML = `<div class="p-3 text-xs text-rose-500 text-center">Search failed (network error).</div>`;
        resultsEl.classList.remove('hidden');
    }
}

function selectEmployee(id, name, employeeNo, designation) {
    document.getElementById('searchResults').classList.add('hidden');
    document.getElementById('employeeSearch').value = '';

    document.getElementById('selectedEmployeeBar').classList.remove('hidden');
    document.getElementById('selectedAvatar').textContent = (name || '?').charAt(0).toUpperCase();
    document.getElementById('selectedName').textContent = name;
    document.getElementById('selectedMeta').textContent = `${employeeNo}${designation ? ' — ' + designation : ''}`;

    currentEmployeeId = id;
    history.replaceState(null, '', `employee_payroll.php?employee_id=${id}`);
    loadEmployee(id);
}

function clearSelection() {
    currentEmployeeId = null;
    document.getElementById('selectedEmployeeBar').classList.add('hidden');
    document.getElementById('employeePanels').classList.add('hidden');
    document.getElementById('employeeSearch').value = '';
    document.getElementById('employeeSearch').focus();
    history.replaceState(null, '', 'employee_payroll.php');
}

async function loadEmployee(id) {
    document.getElementById('employeePanels').classList.add('hidden');
    document.getElementById('loadingState').classList.remove('hidden');

    try {
        const res = await fetch(`${ajaxUrl}?action=load_employee&employee_id=${id}`);
        const data = await res.json();
        if (data.error) {
            toast(data.error, true);
            document.getElementById('loadingState').classList.add('hidden');
            return;
        }
        renderEmployeeData(data);
    } catch (e) {
        toast('Failed to load employee data (network error).', true);
    }
    document.getElementById('loadingState').classList.add('hidden');
}

function renderEmployeeData(data) {
    document.getElementById('componentsHeading').textContent = `${data.employee.name} — Pay Components`;

    document.getElementById('selectedEmployeeBar').classList.remove('hidden');
    document.getElementById('selectedAvatar').textContent = (data.employee.name || '?').charAt(0).toUpperCase();
    document.getElementById('selectedName').textContent = data.employee.name;
    document.getElementById('selectedMeta').textContent = `${data.employee.employee_no}${data.employee.designation ? ' — ' + data.employee.designation : ''}`;

    document.getElementById('annualGrossSalary').value = data.gross ? data.gross.annual_gross_salary : 0;
    if (data.gross && data.gross.updated_at) {
        const monthly = (parseFloat(data.gross.annual_gross_salary) / 12).toLocaleString('en-NG', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        document.getElementById('grossMeta').textContent = `Last updated ${data.gross.updated_at} • Monthly equivalent: ₦${monthly}`;
    } else {
        document.getElementById('grossMeta').textContent = '';
    }

    document.getElementById('annualRentPaid').value = data.rent ? data.rent.annual_rent_paid : 0;
    document.getElementById('rentReceiptReference').value = data.rent ? (data.rent.rent_receipt_reference || '') : '';
    document.getElementById('rentMeta').textContent = (data.rent && data.rent.updated_at) ? `Last updated ${data.rent.updated_at}` : '';

    const tbody = document.getElementById('componentsTbody');
    tbody.innerHTML = data.components.map(c => `
        <tr class="hover:bg-slate-50/50 transition">
            <td class="p-3 font-bold text-slate-900">
                ${escapeHtml(c.name)}
                ${c.is_pct ? `<span class="block text-[9px] font-black uppercase text-indigo-500 mt-0.5">${c.percentage_value}% of gross</span>` : ''}
                <input type="hidden" name="component_id[]" value="${c.component_id}">
            </td>
            <td class="p-3 capitalize text-slate-600">${escapeHtml(c.type)}</td>
            <td class="p-3">
                <input type="number" step="0.01" name="amount_${c.component_id}" value="${c.amount}" class="w-40 text-sm border border-slate-200 rounded-lg px-3 py-1.5">
            </td>
            <td class="p-3">
                <input type="checkbox" name="active_${c.component_id}" ${c.active ? 'checked' : ''} class="rounded w-4 h-4">
            </td>
            <td class="p-3 text-[10px] font-black uppercase text-slate-500">${escapeHtml(c.source)}</td>
        </tr>
    `).join('');

    document.getElementById('employeePanels').classList.remove('hidden');
}

function setButtonLoading(btn, isLoading, loadingLabel = 'Saving...') {
    if (isLoading) {
        btn.dataset.originalHtml = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = `<span class="inline-flex items-center gap-2">
            <svg class="animate-spin h-3.5 w-3.5" viewBox="0 0 24 24" fill="none">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
            </svg>${loadingLabel}</span>`;
    } else {
        btn.disabled = false;
        if (btn.dataset.originalHtml) btn.innerHTML = btn.dataset.originalHtml;
    }
}

async function saveGrossSalary(e) {
    e.preventDefault();
    if (!currentEmployeeId) return false;
    if (!confirm('This will recalculate every percentage-based component below from this gross figure. Continue?')) return false;

    const btn = document.getElementById('btnSaveGross');
    setButtonLoading(btn, true);
    const formData = new FormData(document.getElementById('grossForm'));
    formData.append('employee_id', currentEmployeeId);

    try {
        const res = await fetch(`${ajaxUrl}?action=save_gross_salary`, { method: 'POST', body: formData });
        if (!res.ok) throw new Error(`Server returned ${res.status}`);
        const data = await res.json();
        if (data.error) {
            toast(data.error, true);
        } else {
            toast(data.message);
            renderEmployeeData(data);
        }
    } catch (err) {
        toast('Failed to save -- ' + err.message, true);
    } finally {
        setButtonLoading(btn, false);
    }
    return false;
}

async function saveComponents(e) {
    e.preventDefault();
    if (!currentEmployeeId) return false;

    const btn = document.getElementById('btnSaveComponents');
    setButtonLoading(btn, true);
    const formData = new FormData(document.getElementById('componentsForm'));
    formData.append('employee_id', currentEmployeeId);

    try {
        const res = await fetch(`${ajaxUrl}?action=save_components`, { method: 'POST', body: formData });
        if (!res.ok) throw new Error(`Server returned ${res.status}`);
        const data = await res.json();
        if (data.error) {
            toast(data.error, true);
        } else {
            toast(data.message);
            renderEmployeeData(data);
        }
    } catch (err) {
        toast('Failed to save -- ' + err.message, true);
    } finally {
        setButtonLoading(btn, false);
    }
    return false;
}

async function saveRent(e) {
    e.preventDefault();
    if (!currentEmployeeId) return false;

    const btn = document.getElementById('btnSaveRent');
    setButtonLoading(btn, true);
    const formData = new FormData(document.getElementById('rentForm'));
    formData.append('employee_id', currentEmployeeId);

    try {
        const res = await fetch(`${ajaxUrl}?action=save_rent`, { method: 'POST', body: formData });
        if (!res.ok) throw new Error(`Server returned ${res.status}`);
        const data = await res.json();
        if (data.error) {
            toast(data.error, true);
        } else {
            toast(data.message);
            renderEmployeeData(data);
        }
    } catch (err) {
        toast('Failed to save -- ' + err.message, true);
    } finally {
        setButtonLoading(btn, false);
    }
    return false;
}

// If the page was loaded with ?employee_id=X (e.g. linked from elsewhere), load it directly
if (currentEmployeeId) {
    loadEmployee(currentEmployeeId);
}
</script>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>