<?php
/**
 * Rendered to HTML then passed through dompdf (see PayrollController) —
 * same table-based layout convention as invoices/folio_invoice.php
 * (dompdf's CSS support can't be trusted with float/flex). Line items are
 * the manager's own typed-in allowance/deduction entries, not a computed
 * tax formula — see CreatePayslipLineItemsTable's migration comment.
 *
 * Employee ID/SSNIT/Ghana Card/bank details are real, manager-entered
 * columns on `users` (see AddIdentificationFieldsToUsers) — shown only
 * when set, "—" otherwise, never fabricated. Still deliberately does NOT
 * include attendance/overtime hours — no attendance tracking exists
 * anywhere in this schema, so that couldn't be shown without inventing
 * numbers. Everything below is either a real column (staff identity,
 * tenant identity, the manager's own line items, computed net pay) or a
 * purely cosmetic element (the blank signature lines) that carries no
 * data of its own.
 */
$primaryColor = safe_hex_color($tenant->primary_color ?? null, '#0d6efd');
$logoDataUri  = null;

if (! empty($tenant->logo_path)) {
    $logoFile = WRITEPATH . 'uploads/' . ltrim($tenant->logo_path, '/');

    if (is_file($logoFile)) {
        $mime = guess_mime_type($logoFile);
        $logoDataUri = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($logoFile));
    }
}

$allowances = array_values(array_filter($lineItems, static fn ($item) => $item->type === 'allowance'));
$deductions = array_values(array_filter($lineItems, static fn ($item) => $item->type === 'deduction'));

$statusMeta = $lookups->payrollRunStatuses[$run->status] ?? ['label' => ucfirst($run->status)];
$staffRole  = $staffUser->role ?? null;
$field      = static fn ($value) => $value !== null && $value !== '' ? esc($value) : '—';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
    body { font-family: Helvetica, Arial, sans-serif; font-size: 12px; color: #222; }
    table { width: 100%; border-collapse: collapse; }
    .outer { border: 1px solid #999; }
    .outer > tbody > tr > td { padding: 14px 18px; }
    .layout-table td { border: none; padding: 0; vertical-align: top; }
    .header-cell { text-align: center; border-bottom: 1px solid #999; padding-bottom: 12px !important; }
    .header-cell .hotel { font-size: 20px; font-weight: bold; color: <?= $primaryColor ?>; }
    .header-cell .sub { font-size: 11px; color: #555; margin-top: 2px; }
    .header-cell img { max-height: 46px; float: right; }
    .title-cell { text-align: center; border-bottom: 1px solid #999; font-weight: bold; font-size: 13px; padding: 8px 0 !important; }
    .info-table td { padding: 2px 0; font-size: 11.5px; }
    .info-table .label { width: 130px; color: #444; }
    .info-table .sep { width: 12px; }
    .info-cell { border-bottom: 1px solid #999; padding-bottom: 10px !important; }
    .money-table th, .money-table td { padding: 4px 6px; font-size: 11.5px; }
    .money-table thead th { text-align: left; border-bottom: 1px solid #333; padding-bottom: 4px; }
    .money-table .amt { text-align: right; }
    .money-table .earn-col { width: 50%; padding-right: 14px; vertical-align: top; }
    .money-table .ded-col { width: 50%; padding-left: 14px; vertical-align: top; border-left: 1px solid #999; }
    .totals-row td { border-top: 1px solid #333; font-weight: bold; padding-top: 6px !important; }
    .money-cell { border-bottom: 1px solid #999; }
    .netpay-cell { text-align: center; font-weight: bold; font-size: 13px; padding: 8px 0 !important; border-bottom: 1px solid #999; }
    .currency-note { text-align: center; font-size: 10.5px; color: #555; padding: 6px 0 !important; }
    .sig-table { padding-top: 24px !important; }
    .sig-table td { text-align: center; font-size: 11px; padding-top: 2px; }
    .sig-line { border-top: 1px solid #333; width: 80%; margin: 0 auto 4px; height: 1px; }
    .footer { margin-top: 14px; font-size: 9.5px; color: #888; text-align: center; }
</style>
</head>
<body>

<table class="outer">
    <tr><td class="header-cell">
        <?php if ($logoDataUri): ?><img src="<?= $logoDataUri ?>" alt="Logo"><?php endif; ?>
        <div class="hotel"><?= esc($tenant->hotel_name) ?></div>
        <?php if (! empty($tenant->contact_phone) || ! empty($tenant->contact_email)): ?>
            <div class="sub"><?= esc(trim(($tenant->contact_phone ?? '') . (($tenant->contact_phone && $tenant->contact_email) ? ' · ' : '') . ($tenant->contact_email ?? ''))) ?></div>
        <?php endif; ?>
    </td></tr>

    <tr><td class="title-cell">Payslip for the period of <?= esc(date('F Y', strtotime($run->period_month))) ?></td></tr>

    <tr><td class="info-cell">
        <table class="layout-table">
            <tr>
                <td style="width: 50%;">
                    <table class="info-table">
                        <tr><td class="label">Staff Name</td><td class="sep">:</td><td><?= esc($payslip->full_name_snapshot) ?></td></tr>
                        <tr><td class="label">Role</td><td class="sep">:</td><td><?= esc($lookups->staffRoles[$staffRole]['label'] ?? ($staffRole ? ucfirst(str_replace('_', ' ', $staffRole)) : '—')) ?></td></tr>
                        <tr><td class="label">Employee ID</td><td class="sep">:</td><td><?= $field($staffUser->employee_id ?? null) ?></td></tr>
                        <tr><td class="label">SSNIT Number</td><td class="sep">:</td><td><?= $field($staffUser->ssnit_number ?? null) ?></td></tr>
                        <tr><td class="label">Ghana Card No.</td><td class="sep">:</td><td><?= $field($staffUser->ghana_card_number ?? null) ?></td></tr>
                    </table>
                </td>
                <td style="width: 50%;">
                    <table class="info-table">
                        <tr><td class="label">Bank Name</td><td class="sep">:</td><td><?= $field($staffUser->bank_name ?? null) ?></td></tr>
                        <tr><td class="label">Bank Branch</td><td class="sep">:</td><td><?= $field($staffUser->bank_branch ?? null) ?></td></tr>
                        <tr><td class="label">Account Number</td><td class="sep">:</td><td><?= $field($staffUser->bank_account_number ?? null) ?></td></tr>
                        <tr><td class="label">Payslip Status</td><td class="sep">:</td><td><?= esc($statusMeta['label']) ?></td></tr>
                        <tr><td class="label">Date Issued</td><td class="sep">:</td><td><?= esc($issuedAt) ?></td></tr>
                        <?php if ($run->status === 'paid'): ?>
                        <tr><td class="label">Paid Reference</td><td class="sep">:</td><td><?= esc($run->payment_reference ?: '—') ?></td></tr>
                        <?php endif; ?>
                    </table>
                </td>
            </tr>
        </table>
    </td></tr>

    <tr><td class="money-cell">
        <table class="money-table">
            <tr>
                <td class="earn-col">
                    <table>
                        <thead><tr><th>Earnings</th><th class="amt">Amount</th></tr></thead>
                        <tbody>
                            <tr><td>Basic Pay</td><td class="amt"><?= format_money($payslip->basic_salary, false) ?></td></tr>
                            <?php foreach ($allowances as $item): ?>
                                <tr><td><?= esc($item->label) ?></td><td class="amt"><?= format_money($item->amount, false) ?></td></tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="totals-row"><td>Total Earnings</td><td class="amt"><?= format_money(money_add($payslip->basic_salary, $payslip->total_allowances), false) ?></td></tr>
                        </tfoot>
                    </table>
                </td>
                <td class="ded-col">
                    <table>
                        <thead><tr><th>Deductions</th><th class="amt">Amount</th></tr></thead>
                        <tbody>
                            <?php if (empty($deductions)): ?>
                                <tr><td colspan="2" style="color: #888;">None recorded</td></tr>
                            <?php endif; ?>
                            <?php foreach ($deductions as $item): ?>
                                <tr><td><?= esc($item->label) ?></td><td class="amt"><?= format_money($item->amount, false) ?></td></tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="totals-row"><td>Total Deductions</td><td class="amt"><?= format_money($payslip->total_deductions, false) ?></td></tr>
                        </tfoot>
                    </table>
                </td>
            </tr>
        </table>
    </td></tr>

    <tr><td class="netpay-cell">Net Pay: <?= format_money($payslip->net_pay) ?></td></tr>
    <tr><td class="currency-note">(All figures in Ghana Cedis)</td></tr>

    <tr><td>
        <table class="sig-table">
            <tr>
                <td style="width: 45%;"><div class="sig-line"></div>Employer's Signature</td>
                <td style="width: 10%;"></td>
                <td style="width: 45%;"><div class="sig-line"></div>Employee's Signature</td>
            </tr>
        </table>
    </td></tr>
</table>

<div class="footer">
    <?= esc($tenant->hotel_name) ?> &mdash; Generated by MaxYields PMS on <?= esc($issuedAt) ?>. Record-keeping only; this document does not itself constitute a payment instruction.
</div>

</body>
</html>
