<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<?php
$status   = $lookups->payrollRunStatuses[$run->status] ?? ['label' => ucfirst($run->status), 'badge' => 'secondary'];
$isDraft  = $run->status === 'draft';
$runTotal = '0.00';
foreach ($payslips as $slip) {
    $runTotal = money_add($runTotal, $slip->net_pay);
}
?>

<nav aria-label="breadcrumb" class="mb-2">
    <ol class="breadcrumb small mb-0">
        <li class="breadcrumb-item"><a href="<?= site_url('payroll') ?>" class="text-decoration-none">Payroll</a></li>
        <li class="breadcrumb-item active"><?= esc(date('F Y', strtotime($run->period_month))) ?></li>
    </ol>
</nav>

<div class="d-flex justify-content-between align-items-start mb-3">
    <div>
        <h1 class="h3 mb-1"><?= esc(date('F Y', strtotime($run->period_month))) ?> Payroll</h1>
        <span class="badge bg-<?= $status['badge'] ?>"><?= esc($status['label']) ?></span>
        <span class="text-muted small ms-2"><?= count($payslips) ?> staff · Total net pay <?= format_money($runTotal) ?></span>
    </div>
    <div class="d-flex gap-2">
        <?php if ($isDraft): ?>
            <form action="<?= site_url('payroll/' . $run->id . '/finalize') ?>" method="post" onsubmit="return confirm('Finalize this run? Payslips can no longer be edited afterward.');">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-sm btn-primary"><i class="bi bi-lock me-1"></i>Finalize Run</button>
            </form>
        <?php elseif ($run->status === 'finalized'): ?>
            <form action="<?= site_url('payroll/' . $run->id . '/mark-paid') ?>" method="post" class="d-flex gap-2">
                <?= csrf_field() ?>
                <input type="text" name="payment_reference" class="form-control form-control-sm" placeholder="Payment reference (optional)" style="width: 220px;">
                <button type="submit" class="btn btn-sm btn-success"><i class="bi bi-check2 me-1"></i>Mark as Paid</button>
            </form>
        <?php endif; ?>
    </div>
</div>

<?php if ($run->status === 'paid'): ?>
<div class="alert alert-success small d-flex align-items-center gap-2">
    <i class="bi bi-check2-circle"></i>
    Paid on <?= esc(date('d M Y, g:i a', strtotime($run->paid_at))) ?><?= $run->payment_reference ? ' — ' . esc($run->payment_reference) : '' ?>.
    This is a record-keeping note only — payment itself happened outside this system.
</div>
<?php endif; ?>

<?php if (empty($payslips)): ?>
    <div class="card"><div class="card-body text-center text-muted py-4">No active staff to generate payslips for.</div></div>
<?php endif; ?>

<div class="accordion" id="payslipsAccordion">
    <?php foreach ($payslips as $i => $slip): ?>
        <div class="accordion-item">
            <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#slip<?= $slip->id ?>">
                    <div class="d-flex justify-content-between align-items-center w-100 me-3">
                        <span class="fw-semibold"><?= esc($slip->full_name_snapshot) ?></span>
                        <span class="text-muted small">
                            Basic <?= format_money($slip->basic_salary) ?>
                            · Allowances <?= format_money($slip->total_allowances) ?>
                            · Deductions <?= format_money($slip->total_deductions) ?>
                            · <strong>Net <?= format_money($slip->net_pay) ?></strong>
                        </span>
                    </div>
                </button>
            </h2>
            <div id="slip<?= $slip->id ?>" class="accordion-collapse collapse" data-bs-parent="#payslipsAccordion">
                <div class="accordion-body">
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <?php if ($isDraft): ?>
                        <form action="<?= site_url('payroll/' . $run->id . '/payslips/' . $slip->id) ?>" method="post" class="d-flex align-items-end gap-2">
                            <?= csrf_field() ?>
                            <div>
                                <label class="form-label small mb-1">Basic Salary (GHS)</label>
                                <input type="number" step="0.01" min="0" name="basic_salary" value="<?= esc($slip->basic_salary) ?>" class="form-control form-control-sm" style="width: 160px;">
                            </div>
                            <button type="submit" class="btn btn-sm btn-outline-secondary">Update</button>
                        </form>
                        <?php else: ?>
                        <div class="small text-muted">Basic Salary: <span class="fw-semibold text-body"><?= format_money($slip->basic_salary) ?></span></div>
                        <?php endif; ?>
                        <a href="<?= site_url('payroll/' . $run->id . '/payslips/' . $slip->id . '/pdf') ?>" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="bi bi-file-earmark-pdf me-1"></i>Payslip PDF</a>
                    </div>

                    <?php if (! empty($lineItems[$slip->id])): ?>
                    <div class="table-responsive mb-3">
                        <table class="table table-sm mb-0 small align-middle">
                            <thead><tr><th>Type</th><th>Label</th><th class="text-end">Amount</th><?php if ($isDraft): ?><th></th><?php endif; ?></tr></thead>
                            <tbody>
                            <?php foreach ($lineItems[$slip->id] as $item):
                                $typeMeta = $lookups->payslipLineItemTypes[$item->type] ?? ['label' => ucfirst($item->type), 'badge' => 'secondary'];
                            ?>
                                <tr>
                                    <td><span class="badge bg-<?= $typeMeta['badge'] ?>"><?= esc($typeMeta['label']) ?></span></td>
                                    <td><?= esc($item->label) ?></td>
                                    <td class="text-end"><?= format_money($item->amount) ?></td>
                                    <?php if ($isDraft): ?>
                                    <td class="text-end">
                                        <form action="<?= site_url('payroll/' . $run->id . '/payslips/' . $slip->id . '/line-items/' . $item->id . '/delete') ?>" method="post" class="d-inline">
                                            <?= csrf_field() ?>
                                            <button type="submit" class="btn btn-sm btn-outline-danger" title="Remove"><i class="bi bi-trash"></i></button>
                                        </form>
                                    </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>

                    <?php if ($isDraft): ?>
                    <form action="<?= site_url('payroll/' . $run->id . '/payslips/' . $slip->id . '/line-items') ?>" method="post" class="row g-2 align-items-end">
                        <?= csrf_field() ?>
                        <div class="col-md-3">
                            <label class="form-label small mb-1">Type</label>
                            <select name="type" class="form-select form-select-sm" required>
                                <?php foreach ($lookups->payslipLineItemTypes as $key => $meta): ?>
                                    <option value="<?= esc($key) ?>"><?= esc($meta['label']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small mb-1">Label</label>
                            <input type="text" name="label" class="form-control form-control-sm" placeholder="e.g. Transport allowance, SSNIT" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label small mb-1">Amount (GHS)</label>
                            <input type="number" step="0.01" min="0.01" name="amount" class="form-control form-control-sm" required>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-sm btn-primary w-100"><i class="bi bi-plus-lg me-1"></i>Add</button>
                        </div>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<?= $this->endSection() ?>
