<?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 send payslips.";
    header("Location: dashboard.php");
    exit;
}

$cycleId = (int) ($_GET['cycle_id'] ?? 0);
$stmt = $conn->prepare("SELECT * FROM payroll_cycles WHERE id = ?");
$stmt->bind_param('i', $cycleId);
$stmt->execute();
$cycle = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$cycle) {
    $_SESSION['flash_error'] = "Payroll cycle not found.";
    header("Location: cycles.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();

$totalCount = $conn->query("SELECT COUNT(*) as c FROM payroll_payslip_runs WHERE payroll_cycle_id = $cycleId")->fetch_assoc()['c'];
$pendingCount = $conn->query("
    SELECT COUNT(*) as c
    FROM payroll_payslip_runs pr
    WHERE pr.payroll_cycle_id = $cycleId
    AND pr.id NOT IN (SELECT payroll_run_id FROM payslip_email_log WHERE status = 'sent')
")->fetch_assoc()['c'];
$noEmailCount = $conn->query("
    SELECT COUNT(*) as c
    FROM payroll_payslip_runs pr
    JOIN employees e ON e.id = pr.employee_id
    WHERE pr.payroll_cycle_id = $cycleId AND (e.email IS NULL OR e.email = '')
")->fetch_assoc()['c'];

$employeeRows = $conn->query("
    SELECT pr.id as run_id, e.name, e.email,
        (SELECT l.status FROM payslip_email_log l WHERE l.payroll_run_id = pr.id ORDER BY l.sent_at DESC LIMIT 1) as last_status,
        (SELECT l.sent_at FROM payslip_email_log l WHERE l.payroll_run_id = pr.id ORDER BY l.sent_at DESC LIMIT 1) as last_sent_at,
        (SELECT l.error_message FROM payslip_email_log l WHERE l.payroll_run_id = pr.id ORDER BY l.sent_at DESC LIMIT 1) as last_error
    FROM payroll_payslip_runs pr
    JOIN employees e ON e.id = pr.employee_id
    WHERE pr.payroll_cycle_id = $cycleId
    ORDER BY e.name ASC
");

$allCycles = $conn->query("SELECT id, name, payroll_year, payroll_month FROM payroll_cycles ORDER BY payroll_year DESC, payroll_month DESC");

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

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <div class="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3 mb-4">
        <div>
            <h3 class="text-xs font-black text-slate-900 mb-1"><?= h($cycle['name']); ?> &mdash; Send Payslips</h3>
            <p class="text-[11px] text-slate-400 font-medium">
                Status: <span class="uppercase font-black text-slate-600"><?= str_replace('_',' ', $cycle['status']); ?></span> &bull;
                <?= $totalCount - $pendingCount; ?> of <?= $totalCount; ?> already sent successfully<?= $pendingCount > 0 ? ", $pendingCount pending/failed" : ''; ?><?= $noEmailCount > 0 ? ", $noEmailCount with no email on file (always skipped)" : ''; ?>.
                <?php if (!in_array($cycle['status'], ['approved','paid'])): ?>
                    <span class="text-rose-500">This cycle must be fully approved before sending. <a href="cycle_approve.php?cycle_id=<?= $cycleId; ?>" class="underline">Check approval status</a>.</span>
                <?php endif; ?>
            </p>
        </div>
        <div>
            <label class="text-[9px] font-black text-slate-400 uppercase tracking-wider block mb-1">Month</label>
            <select onchange="window.location = 'send_payslips.php?cycle_id=' + this.value" class="text-xs border border-slate-200 bg-slate-50 rounded-lg px-3 py-2 font-bold text-slate-700 min-w-[180px]">
                <?php while ($ac = $allCycles->fetch_assoc()): ?>
                    <option value="<?= $ac['id']; ?>" <?= (int)$ac['id'] === $cycleId ? 'selected' : ''; ?>><?= h($ac['name']); ?></option>
                <?php endwhile; ?>
            </select>
        </div>
    </div>

    <div class="flex flex-wrap gap-2.5 mb-4">
        <button id="btnSendPending" onclick="startSend('pending')" <?= (!in_array($cycle['status'], ['approved','paid']) || $pendingCount === 0) ? 'disabled' : ''; ?>
            class="bg-emerald-600 hover:bg-emerald-700 disabled:bg-slate-200 disabled:border-slate-200 disabled:cursor-not-allowed text-white disabled:text-slate-400 font-bold px-4 py-2 rounded-lg text-xs transition active:scale-95 border border-emerald-700 disabled:border-slate-200">
            Send to Pending/Failed (<?= $pendingCount; ?>)
        </button>
        <button id="btnResendAll" onclick="startSend('resend_all')" <?= !in_array($cycle['status'], ['approved','paid']) ? 'disabled' : ''; ?>
            class="bg-white border border-rose-200 hover:bg-rose-50 disabled:bg-slate-50 disabled:cursor-not-allowed text-rose-600 disabled:text-slate-300 font-bold px-4 py-2 rounded-lg text-xs transition active:scale-95">
            Force Resend to All (<?= $totalCount; ?>)
        </button>
    </div>

    <!-- Live progress area, hidden until a batch send starts -->
    <div id="progressArea" class="hidden border-t border-slate-100 pt-4 space-y-3">
        <div class="flex items-center justify-between text-xs font-bold text-slate-600">
            <span id="progressLabel">Preparing...</span>
            <span id="progressCount">0 / 0</span>
        </div>
        <div class="w-full bg-slate-100 rounded-full h-2 overflow-hidden">
            <div id="progressBar" class="bg-indigo-600 h-2 rounded-full transition-all duration-200" style="width: 0%"></div>
        </div>
        <div id="skippedNote" class="hidden text-[11px] text-amber-600 font-semibold"></div>
        <div class="max-h-64 overflow-y-auto border border-slate-100 rounded-lg divide-y divide-slate-100" id="liveLog"></div>
        <div id="progressSummary" class="hidden text-xs font-bold text-slate-700 pt-2"></div>
    </div>
</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">Send by Employee</h3>
        <p class="text-[10px] text-slate-400 font-medium mt-0.5">Resend to one person at a time -- doesn't touch anyone else's payslip email.</p>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full min-w-[750px] border-collapse">
            <thead>
                <tr class="bg-slate-50 text-slate-400 uppercase text-[9px] font-black tracking-wider border-b border-slate-100">
                    <th class="p-3 text-left">Employee</th>
                    <th class="p-3 text-left">Email</th>
                    <th class="p-3 text-left">Last Status</th>
                    <th class="p-3 text-left">Last Sent</th>
                    <th class="p-3 text-left">Action</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100 text-xs text-slate-700">
                <?php while ($e = $employeeRows->fetch_assoc()):
                    $hasEmail = !empty($e['email']);
                    $status = $e['last_status'];
                    $badge = $status === 'sent' ? 'bg-emerald-50 text-emerald-700 border-emerald-100' : ($status === 'failed' ? 'bg-rose-50 text-rose-700 border-rose-100' : 'bg-slate-50 text-slate-500 border-slate-100');
                    $label = $status ?: 'never sent';
                ?>
                <tr id="empRow-<?= $e['run_id']; ?>" class="hover:bg-slate-50/50 transition">
                    <td class="p-3 font-bold text-slate-900"><?= h($e['name']); ?></td>
                    <td class="p-3 text-slate-500"><?= $hasEmail ? h($e['email']) : '<span class="text-amber-600 italic">no email on file</span>'; ?></td>
                    <td class="p-3">
                        <span class="status-badge px-2 py-0.5 text-[10px] font-bold border rounded <?= $badge; ?>"><?= h($label); ?></span>
                        <?php if ($status === 'failed' && $e['last_error']): ?>
                            <div class="error-detail text-[10px] text-rose-500 mt-1"><?= h($e['last_error']); ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="p-3 text-slate-400 font-mono text-[11px] last-sent-cell"><?= $e['last_sent_at'] ? date('d M Y H:i', strtotime($e['last_sent_at'])) : '—'; ?></td>
                    <td class="p-3">
                        <button onclick="resendOne(<?= $e['run_id']; ?>, '<?= h(addslashes($e['name'])); ?>')" <?= !$hasEmail ? 'disabled' : ''; ?>
                            class="resend-btn p-1.5 rounded-lg bg-slate-50 border border-slate-200 text-[10px] font-bold text-slate-500 hover:text-indigo-600 hover:border-indigo-300 transition active:scale-95 disabled:text-slate-300 disabled:cursor-not-allowed">
                            <?= $hasEmail ? '↻ Resend' : 'skipped'; ?>
                        </button>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
const ajaxUrl = 'send_payslips_ajax.php';
const cycleId = <?= $cycleId; ?>;

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);
}

async function resendOne(runId, name) {
    if (!confirm(`Resend the payslip email to ${name}?`)) return;

    const row = document.getElementById(`empRow-${runId}`);
    const btn = row.querySelector('.resend-btn');
    const statusBadge = row.querySelector('.status-badge');
    const lastSentCell = row.querySelector('.last-sent-cell');
    const existingErrorDetail = row.querySelector('.error-detail');
    if (existingErrorDetail) existingErrorDetail.remove();

    btn.disabled = true;
    const originalText = btn.textContent;
    btn.textContent = 'Sending...';
    statusBadge.textContent = 'sending';
    statusBadge.className = 'status-badge px-2 py-0.5 text-[10px] font-bold border rounded bg-amber-50 text-amber-700 border-amber-100';

    let result;
    try {
        const res = await fetch(`${ajaxUrl}?action=send_one&cycle_id=${cycleId}&run_id=${runId}`);
        result = await res.json();
    } catch (e) {
        result = { status: 'failed', error: 'Network error contacting server.' };
    }

    btn.disabled = false;
    btn.textContent = originalText;

    const nowLabel = new Date().toLocaleString('en-GB', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
    lastSentCell.textContent = nowLabel;

    if (result.status === 'sent') {
        statusBadge.textContent = 'sent';
        statusBadge.className = 'status-badge px-2 py-0.5 text-[10px] font-bold border rounded bg-emerald-50 text-emerald-700 border-emerald-100';
        toast(`Payslip sent to ${name}.`);
    } else {
        statusBadge.textContent = 'failed';
        statusBadge.className = 'status-badge px-2 py-0.5 text-[10px] font-bold border rounded bg-rose-50 text-rose-700 border-rose-100';
        if (result.error) {
            const errDiv = document.createElement('div');
            errDiv.className = 'error-detail text-[10px] text-rose-500 mt-1';
            errDiv.textContent = result.error;
            statusBadge.insertAdjacentElement('afterend', errDiv);
        }
        toast(`Failed to send to ${name}.`, true);
    }
}

async function startSend(mode) {
    if (mode === 'resend_all') {
        if (!confirm('This will RE-SEND payslip emails to everyone in this cycle, including those who already received one. Continue?')) return;
    } else {
        if (!confirm('Send payslip emails to everyone who hasn\'t successfully received one yet?')) return;
    }

    document.getElementById('btnSendPending').disabled = true;
    document.getElementById('btnResendAll').disabled = true;

    const progressArea = document.getElementById('progressArea');
    const progressLabel = document.getElementById('progressLabel');
    const progressCount = document.getElementById('progressCount');
    const progressBar = document.getElementById('progressBar');
    const skippedNote = document.getElementById('skippedNote');
    const liveLog = document.getElementById('liveLog');
    const progressSummary = document.getElementById('progressSummary');

    progressArea.classList.remove('hidden');
    progressSummary.classList.add('hidden');
    skippedNote.classList.add('hidden');
    liveLog.innerHTML = '';
    progressLabel.textContent = 'Building send queue...';
    progressBar.style.width = '0%';
    progressCount.textContent = '';

    let queueResp;
    try {
        const res = await fetch(`${ajaxUrl}?action=queue&cycle_id=${cycleId}&mode=${mode}`);
        queueResp = await res.json();
    } catch (e) {
        progressLabel.textContent = 'Failed to build send queue (network error).';
        return;
    }

    if (queueResp.error) {
        progressLabel.textContent = queueResp.error;
        document.getElementById('btnSendPending').disabled = false;
        document.getElementById('btnResendAll').disabled = false;
        return;
    }

    const queue = queueResp.queue;
    const skipped = queueResp.skipped;

    if (skipped.length > 0) {
        skippedNote.classList.remove('hidden');
        skippedNote.textContent = `Skipping ${skipped.length} employee(s) with no email on file: ${skipped.map(s => s.name).join(', ')}`;
    }

    if (queue.length === 0) {
        progressLabel.textContent = 'Nothing to send.';
        progressCount.textContent = `0 / 0`;
        document.getElementById('btnSendPending').disabled = false;
        document.getElementById('btnResendAll').disabled = false;
        return;
    }

    let sent = 0, failed = 0;
    for (let i = 0; i < queue.length; i++) {
        const item = queue[i];
        progressLabel.textContent = `Sending to ${item.name}...`;
        progressCount.textContent = `${i + 1} / ${queue.length}`;
        progressBar.style.width = `${Math.round((i / queue.length) * 100)}%`;

        let result;
        try {
            const res = await fetch(`${ajaxUrl}?action=send_one&cycle_id=${cycleId}&run_id=${item.run_id}`);
            result = await res.json();
        } catch (e) {
            result = { name: item.name, email: item.email, status: 'failed', error: 'Network error contacting server.' };
        }

        result.status === 'sent' ? sent++ : failed++;

        const row = document.createElement('div');
        row.className = 'px-4 py-2 flex items-center justify-between text-xs';
        row.innerHTML = `
            <span class="font-bold text-slate-800">${result.name || item.name}</span>
            <span class="text-slate-400 flex-1 px-3 truncate">${result.email || item.email}</span>
            <span class="px-2 py-0.5 text-[10px] font-bold border rounded ${result.status === 'sent' ? 'bg-emerald-50 text-emerald-700 border-emerald-100' : 'bg-rose-50 text-rose-700 border-rose-100'}">${result.status}</span>
        `;
        liveLog.appendChild(row);
        if (result.status !== 'sent' && result.error) {
            const errLine = document.createElement('div');
            errLine.className = 'px-4 pb-2 text-[10px] text-rose-500';
            errLine.textContent = result.error;
            liveLog.appendChild(errLine);
        }
        liveLog.scrollTop = liveLog.scrollHeight;

        progressBar.style.width = `${Math.round(((i + 1) / queue.length) * 100)}%`;
    }

    progressLabel.textContent = 'Done';
    progressCount.textContent = `${queue.length} / ${queue.length}`;
    progressSummary.classList.remove('hidden');
    progressSummary.innerHTML = `<span class="text-emerald-600">${sent} sent</span>` + (failed > 0 ? ` &bull; <span class="text-rose-600">${failed} failed</span>` : '') + (skipped.length > 0 ? ` &bull; <span class="text-amber-600">${skipped.length} skipped (no email)</span>` : '');

    await fetch(`${ajaxUrl}?action=finalize&cycle_id=${cycleId}`);

    document.getElementById('btnSendPending').disabled = false;
    document.getElementById('btnResendAll').disabled = false;

    // Reload after a short pause so the "Send by Employee" table and pending counts reflect the new state
    setTimeout(() => location.reload(), 1500);
}
</script>

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