<?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 pay group 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();

$initialGroupId = isset($_GET['group_id']) ? (int) $_GET['group_id'] : 0;

$pageTitle = 'Pay Group 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 Pay Group</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-3">Search by group name.</p>
    <div class="relative">
        <input type="text" id="groupSearch" autocomplete="off" placeholder="Start typing a group 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="selectedGroupBar" 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 pay group data...</div>

<div id="groupPanel" class="hidden 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 Group Components</h3>
        <p class="text-[10px] text-slate-500 font-semibold mt-1">These amounts apply to every employee in this group who doesn't have an individual override set on their own payroll page.</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 Group</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>

<script>
const ajaxUrl = 'group_payroll_ajax.php';
let currentGroupId = <?= $initialGroupId ?: '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('groupSearch').addEventListener('input', function() {
    const q = this.value.trim();
    clearTimeout(searchDebounce);
    searchDebounce = setTimeout(() => runSearch(q), 250);
});

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

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

async function runSearch(q) {
    const resultsEl = document.getElementById('searchResults');
    try {
        const res = await fetch(`${ajaxUrl}?action=search_groups&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 pay groups.</div>`;
        } else {
            resultsEl.innerHTML = results.map(r => `
                <button type="button" onclick="selectGroup(${r.id}, '${escapeHtml(r.name).replace(/'/g, "\\'")}', ${r.employee_count})"
                    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)}</p>
                        <p class="text-[10px] text-slate-400 truncate">${r.employee_count} employee${r.employee_count == 1 ? '' : 's'}</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 selectGroup(id, name, employeeCount) {
    document.getElementById('searchResults').classList.add('hidden');
    document.getElementById('groupSearch').value = '';

    currentGroupId = id;
    history.replaceState(null, '', `group_payroll.php?group_id=${id}`);
    loadGroup(id);
}

function clearSelection() {
    currentGroupId = null;
    document.getElementById('selectedGroupBar').classList.add('hidden');
    document.getElementById('groupPanel').classList.add('hidden');
    document.getElementById('groupSearch').value = '';
    document.getElementById('groupSearch').focus();
    history.replaceState(null, '', 'group_payroll.php');
}

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

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

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

    document.getElementById('selectedGroupBar').classList.remove('hidden');
    document.getElementById('selectedAvatar').textContent = (data.group.name || '?').charAt(0).toUpperCase();
    document.getElementById('selectedName').textContent = data.group.name;
    document.getElementById('selectedMeta').textContent = `${data.group.employee_count} employee${data.group.employee_count == 1 ? '' : 's'} in this group`;

    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 (per employee)</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>
        </tr>
    `).join('');

    document.getElementById('groupPanel').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 saveComponents(e) {
    e.preventDefault();
    if (!currentGroupId) return false;

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

    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);
            renderGroupData(data);
        }
    } catch (err) {
        toast('Failed to save -- ' + err.message, true);
    } finally {
        setButtonLoading(btn, false);
    }
    return false;
}

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

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