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

$runId = (int) ($_GET['run_id'] ?? 0);

$stmt = $conn->prepare("
    SELECT pr.*, e.name, e.employee_no, e.designation, e.department_id, e.bank_name, e.account_number, e.account_name, e.email,
           pc.name as cycle_name, pc.start_date, pc.end_date
    FROM payroll_payslip_runs pr
    JOIN employees e ON e.id = pr.employee_id
    JOIN payroll_cycles pc ON pc.id = pr.payroll_cycle_id
    WHERE pr.id = ?
");
$stmt->bind_param('i', $runId);
$stmt->execute();
$run = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$run) {
    $_SESSION['flash_error'] = "Payslip not found.";
    header("Location: cycles.php");
    exit;
}

// Non-admins may only view their own payslip
if (!$isAdmin) {
    $selfCheck = $conn->query("SELECT id FROM employees WHERE user_id = " . (int)$_SESSION['user_id'] . " LIMIT 1")->fetch_assoc();
    if (!$selfCheck || (int)$selfCheck['id'] !== (int)$run['employee_id']) {
        $_SESSION['flash_error'] = "You can only view your own payslip.";
        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();

require __DIR__ . '/includes/PayrollEngine.php';

$items = $conn->query("SELECT * FROM payroll_payslip_items WHERE payroll_run_id = $runId ORDER BY type ASC, id ASC");
$earnings = [];
$deductions = [];
while ($item = $items->fetch_assoc()) {
    if ($item['type'] === 'earning') $earnings[] = $item;
    else $deductions[] = $item;
}

// Recompute the attendance breakdown live, bounded by THIS cycle's own
// start_date/end_date -- the exact same figures the engine used to
// derive the LOP amount already stored on this payslip.
$engine = new PayrollEngine($conn);
$attendance = $engine->calculateAttendanceForRange((int) $run['employee_id'], $run['start_date'], $run['end_date']);
$dailyRate = $attendance['scheduled_days'] > 0 ? $run['gross_earnings'] / $attendance['scheduled_days'] : 0;

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

<div class="bg-white border border-slate-200/80 rounded-xl p-6 sm:p-8 shadow-xs print:shadow-none print:border-0" id="payslip">
    <div class="flex items-start justify-between border-b border-slate-200 pb-5 mb-5">
        <div>
            <h2 class="text-lg font-black text-slate-900">Payslip</h2>
            <p class="text-xs text-slate-500 font-semibold"><?= h($run['cycle_name']); ?> &bull; <?= date('d M', strtotime($run['start_date'])); ?> &ndash; <?= date('d M Y', strtotime($run['end_date'])); ?></p>
        </div>
        <button onclick="window.print()" class="print:hidden bg-slate-900 hover:bg-slate-800 text-white text-xs font-black uppercase px-4 py-2 rounded-lg transition active:scale-95 border border-slate-950">Print / Save PDF</button>
    </div>

    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-6 text-sm">
        <div>
            <p class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Employee</p>
            <p class="font-bold text-slate-900"><?= h($run['name']); ?> (<?= h($run['employee_no']); ?>)</p>
            <p class="text-slate-600"><?= h($run['designation']); ?></p>
        </div>
        <div>
            <p class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Bank Details</p>
            <p class="text-slate-700"><?= h($run['bank_name'] ?: 'Not on file'); ?></p>
            <p class="text-slate-700"><?= h($run['account_number'] ?: ''); ?> <?= h($run['account_name'] ? '('.$run['account_name'].')' : ''); ?></p>
        </div>
    </div>

    <div class="bg-slate-50 border border-slate-200 rounded-xl p-4 mb-6">
        <h4 class="text-[10px] font-black text-slate-500 uppercase tracking-wider mb-3">Attendance This Cycle</h4>
        <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center mb-3">
            <div>
                <p class="text-lg font-black text-slate-900"><?= (int) $attendance['scheduled_days']; ?></p>
                <p class="text-[9px] font-bold text-slate-500 uppercase">Scheduled</p>
            </div>
            <div>
                <p class="text-lg font-black text-emerald-700"><?= (int) $attendance['days_worked']; ?></p>
                <p class="text-[9px] font-bold text-slate-500 uppercase">Worked</p>
            </div>
            <div>
                <p class="text-lg font-black <?= $attendance['absent_days'] > 0 ? 'text-rose-700' : 'text-slate-400'; ?>"><?= (int) $attendance['absent_days']; ?></p>
                <p class="text-[9px] font-bold text-slate-500 uppercase">Absent</p>
            </div>
            <div>
                <p class="text-lg font-black text-rose-700">₦<?= number_format($run['lop_amount'], 2); ?></p>
                <p class="text-[9px] font-bold text-slate-500 uppercase">Loss of Pay</p>
            </div>
        </div>
        <?php if ($run['lop_amount'] > 0): ?>
        <p class="text-[10px] text-slate-500 font-mono text-center pt-3 border-t border-slate-200">
            Daily Rate (₦<?= number_format($run['gross_earnings'], 2); ?> ÷ <?= (int) $attendance['scheduled_days']; ?> scheduled days = ₦<?= number_format($dailyRate, 2); ?>) &times; <?= (int) $attendance['absent_days']; ?> absent day<?= $attendance['absent_days'] == 1 ? '' : 's'; ?> = ₦<?= number_format($run['lop_amount'], 2); ?>
        </p>
        <?php else: ?>
        <p class="text-[10px] text-slate-400 text-center pt-3 border-t border-slate-200">No unexcused absences this cycle -- no Loss of Pay applied.</p>
        <?php endif; ?>
    </div>

    <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
        <div>
            <h4 class="text-[10px] font-black text-emerald-700 uppercase tracking-wider mb-2">Earnings</h4>
            <table class="w-full text-sm">
                <?php foreach ($earnings as $e): ?>
                <tr class="border-b border-slate-100">
                    <td class="py-2 text-slate-700"><?= h($e['name']); ?></td>
                    <td class="py-2 text-right font-semibold text-slate-900">₦<?= number_format($e['amount'], 2); ?></td>
                </tr>
                <?php endforeach; ?>
                <tr>
                    <td class="py-2 font-black text-slate-900">Gross Earnings</td>
                    <td class="py-2 text-right font-black text-slate-900">₦<?= number_format($run['gross_earnings'], 2); ?></td>
                </tr>
            </table>
        </div>
        <div>
            <h4 class="text-[10px] font-black text-rose-700 uppercase tracking-wider mb-2">Deductions</h4>
            <table class="w-full text-sm">
                <?php foreach ($deductions as $d): ?>
                <tr class="border-b border-slate-100">
                    <td class="py-2 text-slate-700"><?= h($d['name']); ?></td>
                    <td class="py-2 text-right font-semibold text-slate-900">₦<?= number_format($d['amount'], 2); ?></td>
                </tr>
                <?php endforeach; ?>
                <tr>
                    <td class="py-2 font-black text-slate-900">Total Deductions</td>
                    <td class="py-2 text-right font-black text-slate-900">₦<?= number_format($run['total_deductions'], 2); ?></td>
                </tr>
            </table>
        </div>
    </div>

    <div class="mt-6 pt-5 border-t-2 border-slate-900 flex items-center justify-between">
        <p class="text-sm font-black text-slate-900 uppercase tracking-wider">Net Pay</p>
        <p class="text-2xl font-black text-emerald-700">₦<?= number_format($run['net_pay'], 2); ?></p>
    </div>

    <p class="text-[9px] text-slate-400 mt-6 font-mono">Generated by Core HR Engine Payroll Module &bull; Rent relief applied: ₦<?= number_format($run['rent_relief_applied'],2); ?>/yr</p>
</div>

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