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

if (!$isAdmin) {
    $_SESSION['flash_error'] = "You don't have permission to process payroll.";
    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;
}

// Release the session lock on plain page views; the POST branch below still
// needs to write flash data, so it keeps the session open for itself.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    session_write_close();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['run_payroll'])) {
    $groupId = $_POST['group_id'] !== '' ? (int) $_POST['group_id'] : null;
    $engine = new PayrollEngine($conn);
    $results = $engine->runCycle($cycleId, $groupId);
    $errors = array_filter($results, fn($r) => isset($r['error']));
    if (empty($errors)) {
        $_SESSION['flash_success'] = count($results) . " payslip(s) generated for '" . $cycle['name'] . "'. It's now pending approval.";
    } else {
        $_SESSION['flash_error'] = count($errors) . " employee(s) failed to process. Check their records.";
    }
    // Carry the same scope into the view filter so the list below reflects what you just ran
    $redirectGroup = $groupId ? "&group_id=$groupId" : '';
    header("Location: run_cycle.php?cycle_id=$cycleId" . $redirectGroup);
    exit;
}

// View filter -- independent of running, lets you browse the list by group without recalculating
$viewGroupId = isset($_GET['group_id']) && $_GET['group_id'] !== '' ? (int) $_GET['group_id'] : null;

$groups = $conn->query("SELECT * FROM groups ORDER BY name ASC");

$runsSql = "
    SELECT pr.*, e.name, e.employee_no
    FROM payroll_payslip_runs pr
    JOIN employees e ON e.id = pr.employee_id
    WHERE pr.payroll_cycle_id = $cycleId
";
if ($viewGroupId) {
    $runsSql .= " AND pr.group_id = $viewGroupId";
}
$runsSql .= " ORDER BY e.name ASC";
$runs = $conn->query($runsSql);
$runCount = $runs->num_rows;

$pageTitle = 'Process Payroll Cycle';
$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"><?= h($cycle['name']); ?></h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-4"><?= date('d M', strtotime($cycle['start_date'])); ?> &ndash; <?= date('d M Y', strtotime($cycle['end_date'])); ?> &bull; Status: <span class="uppercase font-black"><?= str_replace('_',' ',$cycle['status']); ?></span></p>

    <form method="POST" class="flex flex-col sm:flex-row gap-3 items-end" onsubmit="return confirm('Run payroll for this scope? This recalculates all matching payslips.');">
        <div class="flex-1">
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Scope</label>
            <select name="group_id" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <option value="">All Employees</option>
                <?php $groups->data_seek(0); while ($g = $groups->fetch_assoc()): ?>
                    <option value="<?= $g['id']; ?>" <?= $viewGroupId === (int)$g['id'] ? 'selected' : ''; ?>><?= h($g['name']); ?> only</option>
                <?php endwhile; ?>
            </select>
        </div>
        <button type="submit" name="run_payroll" 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">
            Run / Recalculate Payroll
        </button>
    </form>
</div>

<div class="bg-white border border-slate-200 rounded-xl shadow-xs overflow-hidden">
    <div class="p-4 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
        <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight">Generated Payslips (<?= $runCount; ?>)<?php if ($viewGroupId): $gName = $conn->query("SELECT name FROM groups WHERE id = $viewGroupId")->fetch_assoc()['name'] ?? ''; ?> &mdash; <span class="text-indigo-700"><?= h($gName); ?></span><?php endif; ?></h3>
        <form method="GET" class="flex items-center gap-2">
            <input type="hidden" name="cycle_id" value="<?= $cycleId; ?>">
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Filter view</label>
            <select name="group_id" onchange="this.form.submit()" class="text-sm border border-slate-200 rounded-lg px-3 py-1.5">
                <option value="">All Employees</option>
                <?php $groups->data_seek(0); while ($g = $groups->fetch_assoc()): ?>
                    <option value="<?= $g['id']; ?>" <?= $viewGroupId === (int)$g['id'] ? 'selected' : ''; ?>><?= h($g['name']); ?></option>
                <?php endwhile; ?>
            </select>
        </form>
    </div>
    <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">Employee</th>
                    <th class="text-left p-3">Gross</th>
                    <th class="text-left p-3">Absent Days</th>
                    <th class="text-left p-3">LOP</th>
                    <th class="text-left p-3">Surcharge</th>
                    <th class="text-left p-3">PAYE</th>
                    <th class="text-left p-3">Pension</th>
                    <th class="text-left p-3">NHF</th>
                    <th class="text-left p-3">NHIS</th>
                    <th class="text-left p-3">Net Pay</th>
                    <th class="text-left p-3">Slip</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php while ($r = $runs->fetch_assoc()): ?>
                <tr class="hover:bg-slate-50/50 transition">
                    <td class="p-3 font-bold text-slate-900"><?= h($r['name']); ?> <span class="text-slate-400 font-normal">(<?= h($r['employee_no']); ?>)</span></td>
                    <td class="p-3">₦<?= number_format($r['gross_earnings'], 2); ?></td>
                    <td class="p-3 <?= $r['absent_days'] > 0 ? 'text-rose-700 font-bold' : 'text-slate-400'; ?>"><?= rtrim(rtrim(number_format($r['absent_days'], 2), '0'), '.') ?: '0'; ?></td>
                    <td class="p-3 <?= $r['lop_amount'] > 0 ? 'text-rose-700 font-bold' : 'text-slate-400'; ?>">₦<?= number_format($r['lop_amount'], 2); ?></td>
                    <td class="p-3 <?= $r['surcharge_amount'] > 0 ? 'text-rose-700 font-bold' : 'text-slate-400'; ?>">₦<?= number_format($r['surcharge_amount'], 2); ?></td>
                    <td class="p-3">₦<?= number_format($r['paye_tax'], 2); ?></td>
                    <td class="p-3">₦<?= number_format($r['pension_employee'], 2); ?></td>
                    <td class="p-3">₦<?= number_format($r['nhf'], 2); ?></td>
                    <td class="p-3">₦<?= number_format($r['nhis'], 2); ?></td>
                    <td class="p-3 font-black text-emerald-700">₦<?= number_format($r['net_pay'], 2); ?></td>
                    <td class="p-3"><a href="payslip.php?run_id=<?= $r['id']; ?>" class="text-indigo-600 font-bold text-xs hover:underline active:scale-95 transition inline-block">View</a></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

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