<?php
$monthNames = ['', 'January','February','March','April','May','June','July','August','September','October','November','December'];
$statusBadge = ['DRAFT' => 'badge-gray', 'FINALIZED' => 'badge-gold', 'PAID' => 'badge-green'];
$totalNet = array_sum(array_column($run['items'], 'net_pay'));
$totalUnpaid = array_sum(array_map(fn($i) => $i['is_paid'] ? 0 : $i['net_pay'], $run['items']));
?>
<a href="<?= Router::url('payroll') ?>" style="font-size:13px;color:var(--color-text-muted);"><i class="fa-solid fa-arrow-left"></i> Back to Payroll</a>

<div class="panel" style="margin-top:14px;">
    <div class="panel-head">
        <h3><?= e($monthNames[$run['period_month']]) ?> <?= e($run['period_year']) ?> Payroll</h3>
        <span class="badge <?= $statusBadge[$run['status']] ?? 'badge-gray' ?>"><?= e($run['status']) ?></span>
    </div>
    <div style="display:flex;gap:24px;font-size:13px;color:var(--color-text-muted);">
        <div>Total Net Pay: <strong style="color:var(--color-text);"><?= formatMoney($totalNet) ?></strong></div>
        <div>Unpaid Balance: <strong style="color:var(--color-danger);"><?= formatMoney($totalUnpaid) ?></strong></div>
    </div>
</div>

<div class="panel" style="padding:0;overflow-x:auto;">
<table class="data-table">
<thead><tr><th>Staff</th><th>Days Present</th><th>Days Absent</th><th>Basic</th><th>Additions</th><th>Deductions</th><th>Net Pay</th><th>Status</th><th></th></tr></thead>
<tbody>
<?php foreach ($run['items'] as $it): ?>
<tr>
    <td><strong><?= e($it['full_name']) ?></strong><div style="color:var(--color-text-muted);font-size:11px;"><?= e($it['role_name']) ?></div></td>
    <td><?= number_format((float) $it['days_present'], 1) ?></td>
    <td><?= (int) $it['days_absent'] ?></td>
    <td><?= formatMoney((float) $it['basic_amount']) ?></td>
    <td style="color:var(--color-success);"><?= (float) $it['additions'] > 0 ? '+' . formatMoney((float) $it['additions']) : '—' ?></td>
    <td style="color:var(--color-danger);"><?= (float) $it['deductions'] > 0 ? '-' . formatMoney((float) $it['deductions']) : '—' ?></td>
    <td><strong><?= formatMoney((float) $it['net_pay']) ?></strong></td>
    <td><?= $it['is_paid'] ? '<span class="badge badge-green"><i class="fa-solid fa-circle-check"></i> Paid</span>' : '<span class="badge badge-gray">Unpaid</span>' ?></td>
    <td style="white-space:nowrap;">
        <?php if ($run['status'] === 'DRAFT' && Auth::can('payroll', 'edit')): ?>
        <button type="button" class="btn btn-secondary" style="padding:5px 10px;font-size:12px;" onclick="rmsOpenModal('rmsEditItem<?= $it['id'] ?>')"><i class="fa-solid fa-pen"></i></button>
        <?php endif; ?>
        <?php if (!$it['is_paid'] && $run['status'] !== 'DRAFT' && Auth::can('payroll', 'edit')): ?>
        <button type="button" class="btn btn-secondary" style="padding:5px 10px;font-size:12px;" onclick="rmsOpenModal('rmsPayItem<?= $it['id'] ?>')"><i class="fa-solid fa-money-bill"></i></button>
        <?php endif; ?>
    </td>
</tr>
<?php endforeach; ?>
<?php if (empty($run['items'])): ?>
<tr><td colspan="9" style="text-align:center;color:var(--color-text-muted);padding:30px;">No staff in this run.</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>

<div style="display:flex;gap:10px;margin-top:16px;">
    <?php if ($run['status'] === 'DRAFT' && Auth::can('payroll', 'edit')): ?>
    <form method="POST" action="<?= Router::url('payroll/finalize') ?>" onsubmit="return confirm('Finalize this payroll run? Amounts cannot be edited after this.');">
        <?= $csrf ?>
        <input type="hidden" name="id" value="<?= $run['id'] ?>">
        <button type="submit" class="btn btn-primary"><i class="fa-solid fa-lock"></i> Finalize Run</button>
    </form>
    <?php endif; ?>

    <?php if ($run['status'] === 'FINALIZED' && $totalUnpaid > 0 && Auth::can('payroll', 'edit')): ?>
    <button type="button" class="btn btn-primary" onclick="rmsOpenModal('rmsPayAllModal')"><i class="fa-solid fa-money-bill-wave"></i> Pay All Unpaid</button>
    <?php endif; ?>
</div>

<!-- Edit item modals -->
<?php foreach ($run['items'] as $it): if ($run['status'] !== 'DRAFT' || !Auth::can('payroll', 'edit')) continue; ?>
<div class="rms-modal-overlay" id="rmsEditItem<?= $it['id'] ?>">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-pen" style="color:var(--color-teal);margin-right:6px;"></i><?= e($it['full_name']) ?></h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsEditItem<?= $it['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('payroll/items/update') ?>">
            <?= $csrf ?>
            <input type="hidden" name="item_id" value="<?= $it['id'] ?>">
            <input type="hidden" name="run_id" value="<?= $run['id'] ?>">
            <div style="font-size:12.5px;color:var(--color-text-muted);margin-bottom:10px;">Basic: <?= formatMoney((float) $it['basic_amount']) ?></div>
            <div class="form-group"><label>Additions (bonus, OT)</label><input type="number" step="0.01" name="additions" class="form-control" value="<?= e((string) $it['additions']) ?>"></div>
            <div class="form-group"><label>Deductions (loans, EPF)</label><input type="number" step="0.01" name="deductions" class="form-control" value="<?= e((string) $it['deductions']) ?>"></div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-floppy-disk"></i> Save</button>
        </form>
    </div>
</div>
<?php endforeach; ?>

<!-- Pay single item modals -->
<?php foreach ($run['items'] as $it): if ($it['is_paid'] || $run['status'] === 'DRAFT' || !Auth::can('payroll', 'edit')) continue; ?>
<div class="rms-modal-overlay" id="rmsPayItem<?= $it['id'] ?>">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-money-bill" style="color:var(--color-success);margin-right:6px;"></i>Pay <?= e($it['full_name']) ?></h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsPayItem<?= $it['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('payroll/pay-item') ?>">
            <?= $csrf ?>
            <input type="hidden" name="item_id" value="<?= $it['id'] ?>">
            <input type="hidden" name="run_id" value="<?= $run['id'] ?>">
            <div style="font-size:14px;font-weight:700;margin-bottom:12px;">Net Pay: <?= formatMoney((float) $it['net_pay']) ?></div>
            <div class="form-group">
                <label>Pay From</label>
                <select name="finance_account_id" class="form-control" required>
                    <?php foreach ($financeAccounts as $fa): ?>
                    <option value="<?= $fa['id'] ?>"><?= e($fa['account_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-check"></i> Confirm Payment</button>
        </form>
    </div>
</div>
<?php endforeach; ?>

<!-- Pay all modal -->
<?php if ($run['status'] === 'FINALIZED' && Auth::can('payroll', 'edit')): ?>
<div class="rms-modal-overlay" id="rmsPayAllModal">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-money-bill-wave" style="color:var(--color-success);margin-right:6px;"></i>Pay All Unpaid</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsPayAllModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('payroll/pay-all') ?>">
            <?= $csrf ?>
            <input type="hidden" name="id" value="<?= $run['id'] ?>">
            <div style="font-size:14px;font-weight:700;margin-bottom:12px;">Total: <?= formatMoney($totalUnpaid) ?></div>
            <div class="form-group">
                <label>Pay From</label>
                <select name="finance_account_id" class="form-control" required>
                    <?php foreach ($financeAccounts as $fa): ?>
                    <option value="<?= $fa['id'] ?>"><?= e($fa['account_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;" onclick="return confirm('Pay all unpaid staff for this period?');"><i class="fa-solid fa-check"></i> Confirm — Pay All</button>
        </form>
    </div>
</div>
<?php endif; ?>
