<?php $this->start('body'); ?>
<?php $p = $this->data['p']; $records = $this->data['records'];
$bg = ['draft'=>'secondary','computed'=>'info','approved'=>'warning','paid'=>'success','void'=>'dark'][$p['status']] ?? 'secondary';
$canEdit = in_array($p['status'], ['draft','computed'], true);
?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-semibold"><i class="fas fa-money-check-alt me-2 text-muted"></i><span class="font-monospace"><?= htmlspecialchars($p['period_no']); ?></span>
      <span class="badge bg-<?= $bg; ?> ms-2" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars($p['status']); ?></span>
    </h5>
    <div class="text-muted small"><?= humanDate($p['period_start']); ?> → <?= humanDate($p['period_end']); ?>
      <?php if ($p['approved_at']): ?> · approved <?= humanDateTime($p['approved_at']); ?><?php endif; ?>
      <?php if ($p['paid_at']):     ?> · paid <?= humanDateTime($p['paid_at']); ?><?php endif; ?>
    </div>
  </div>
  <a href="<?= PROOT; ?>Payroll" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<?= flashHtml(); ?>

<?php if ($p['status'] === 'void' && $p['void_reason']): ?>
  <div class="alert alert-dark py-2 small"><strong>Void:</strong> <?= htmlspecialchars($p['void_reason']); ?></div>
<?php endif; ?>

<!-- KPI strip -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2"><div class="text-uppercase text-muted small">Drivers</div><div class="fs-4 fw-bold"><?= (int)$p['driver_count']; ?></div></div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2"><div class="text-uppercase text-muted small">Gross</div><div class="fs-4 fw-bold">TZS <?= number_format((float)$p['total_gross'], 0); ?></div></div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2"><div class="text-uppercase text-muted small">Deductions</div><div class="fs-4 fw-bold text-danger">TZS <?= number_format((float)$p['total_deductions'], 0); ?></div></div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2"><div class="text-uppercase text-muted small">Net pay</div><div class="fs-4 fw-bold text-success">TZS <?= number_format((float)$p['total_net'], 0); ?></div><div class="small text-muted">+ TZS <?= number_format((float)$p['total_employer'], 0); ?> employer</div></div></div></div>
</div>

<!-- Action bar -->
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 d-flex flex-wrap gap-2 align-items-center">
    <span class="text-uppercase text-muted small me-2"><i class="fas fa-play-circle me-1"></i>Actions</span>
    <?php if (in_array($p['status'], ['draft','computed'], true)): ?>
      <form method="POST" action="<?= PROOT; ?>Payroll/compute/<?= (int)$p['c0d']; ?>" class="d-inline"><?= csrf_field(); ?>
        <button class="btn btn-sm btn-info text-white"><i class="fas fa-calculator me-1"></i><?= $p['status'] === 'draft' ? 'Compute' : 'Recompute'; ?></button>
      </form>
    <?php endif; ?>
    <?php if ($p['status'] === 'computed'): ?>
      <button type="button" class="btn btn-sm btn-warning" onclick="doApprove()"><i class="fas fa-check me-1"></i>Approve (post accrual JE)</button>
    <?php endif; ?>
    <?php if ($p['status'] === 'approved'): ?>
      <button type="button" class="btn btn-sm btn-success" onclick="doPay()"><i class="fas fa-hand-holding-usd me-1"></i>Mark paid</button>
    <?php endif; ?>
    <?php if ($p['accrual_je_id']): ?>
      <a href="<?= PROOT; ?>Journals/view/<?= (int)$p['accrual_je_id']; ?>" class="btn btn-sm btn-outline-primary ms-auto"><i class="fas fa-file-alt me-1"></i>Accrual JE</a>
    <?php endif; ?>
    <?php if ($p['payment_je_id']): ?>
      <a href="<?= PROOT; ?>Journals/view/<?= (int)$p['payment_je_id']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-file-alt me-1"></i>Payment JE</a>
    <?php endif; ?>
    <?php if (!empty($records)): ?>
      <a href="<?= PROOT; ?>Payroll/payslipsBatch/<?= (int)$p['c0d']; ?>" target="_blank" class="btn btn-sm btn-outline-primary ms-auto"><i class="fas fa-file-pdf me-1"></i>Payslips (all)</a>
    <?php endif; ?>
    <?php if ($p['status'] !== 'void' && $p['status'] !== 'paid'): ?>
      <button type="button" class="btn btn-sm btn-outline-danger" onclick="doVoid()"><i class="fas fa-ban me-1"></i>Void period</button>
    <?php endif; ?>
  </div>
</div>

<!-- Records -->
<?php if (empty($records)): ?>
  <div class="card border-0 shadow-sm"><div class="card-body text-center text-muted py-5">
    <?php if ($p['status'] === 'draft'): ?>
      Draft period — click <strong>Compute</strong> to generate records for every active driver.
    <?php else: ?>
      No records.
    <?php endif; ?>
  </div></div>
<?php else: ?>
  <div class="card border-0 shadow-sm">
    <div class="table-responsive">
      <table class="table table-sm mb-0 align-middle">
        <thead class="table-light">
          <tr>
            <th>Driver</th><th class="money">Trips</th><th class="money">Base</th><th class="money">Comm.</th>
            <th class="money">Allow.</th><th class="money">Gross</th>
            <th class="money">PAYE</th><th class="money">NSSF(ee)</th><th class="money">HI</th><th class="money">Other</th>
            <th class="money">Net</th><th class="text-end"></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($records as $r): ?>
            <tr>
              <td class="small"><a href="<?= PROOT; ?>Drivers/view/<?= (int)$r['driver_id']; ?>" class="fw-semibold text-decoration-none"><?= htmlspecialchars($r['full_name']); ?></a>
                <?php if ($r['employee_no']): ?><div class="text-muted small"><?= htmlspecialchars($r['employee_no']); ?></div><?php endif; ?></td>
              <td class="money small"><?= (int)$r['trip_count']; ?><?php if ((float)$r['trip_revenue'] > 0): ?><div class="text-muted small"><?= number_format((float)$r['trip_revenue'], 0); ?></div><?php endif; ?></td>
              <td class="money small"><?= number_format((float)$r['base_salary'], 0); ?></td>
              <td class="money small"><?= number_format((float)$r['commission'], 0); ?></td>
              <td class="money small"><?= number_format((float)$r['allowances'], 0); ?></td>
              <td class="money fw-semibold"><?= number_format((float)$r['gross_pay'], 0); ?></td>
              <td class="money small text-danger"><?= number_format((float)$r['paye'], 0); ?></td>
              <td class="money small text-danger"><?= number_format((float)$r['nssf_ee'], 0); ?></td>
              <td class="money small text-danger"><?= number_format((float)$r['health_ins'], 0); ?></td>
              <td class="money small text-danger"><?= number_format((float)$r['other_deductions'], 0); ?></td>
              <td class="money fw-bold text-success"><?= number_format((float)$r['net_pay'], 0); ?></td>
              <td class="text-end">
                <a href="<?= PROOT; ?>Payroll/payslipPdf/<?= (int)$r['c0d']; ?>" target="_blank" class="btn btn-sm btn-outline-primary" title="Payslip (PDF)"><i class="fas fa-file-pdf"></i></a>
                <?php if ($canEdit): ?>
                  <button type="button" class="btn btn-sm btn-outline-primary" onclick='editRecord(<?= (int)$r['c0d']; ?>, <?= (float)$r['allowances']; ?>, <?= (float)$r['other_earnings']; ?>, <?= (float)$r['other_deductions']; ?>)'><i class="fas fa-pen"></i></button>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
        <tfoot class="table-light">
          <tr>
            <th>Totals</th><th></th><th></th><th></th><th></th>
            <th class="money"><?= number_format((float)$p['total_gross'], 0); ?></th>
            <th></th><th></th><th></th>
            <th class="money text-danger"><?= number_format((float)$p['total_deductions'], 0); ?></th>
            <th class="money text-success"><?= number_format((float)$p['total_net'], 0); ?></th>
            <th></th>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
<?php endif; ?>

<!-- Hidden forms -->
<form id="approveForm" method="POST" action="<?= PROOT; ?>Payroll/approve/<?= (int)$p['c0d']; ?>" class="d-none"><?= csrf_field(); ?></form>
<form id="payForm"     method="POST" action="<?= PROOT; ?>Payroll/pay/<?= (int)$p['c0d']; ?>"     class="d-none"><?= csrf_field(); ?><input type="hidden" name="method" id="fPayMethod"></form>
<form id="voidForm"    method="POST" action="<?= PROOT; ?>Payroll/voidPeriod/<?= (int)$p['c0d']; ?>" class="d-none"><?= csrf_field(); ?><input type="hidden" name="reason" id="fVoidReason"></form>
<form id="recordForm"  method="POST" action="" class="d-none"><?= csrf_field(); ?>
  <input type="hidden" name="allowances"       id="fAllow">
  <input type="hidden" name="other_earnings"   id="fOtherE">
  <input type="hidden" name="other_deductions" id="fOtherD">
  <input type="hidden" name="notes"            id="fRNotes">
</form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
const PROOT = '<?= PROOT; ?>';
function doApprove() {
    $.confirm({ title: 'Approve payroll?', content: 'Posts the accrual JE (salaries, statutory expenses) and locks the records.<br>You can still <strong>Void</strong> before marking paid.', type: 'orange',
        buttons: { go: { text: 'Approve', btnClass: 'btn-warning', action: () => document.getElementById('approveForm').submit() }, back: function(){} } });
}
function doPay() {
    $.confirm({ title: 'Mark payroll paid?',
        content: '<div class="mb-2 small text-muted">Records the payment JE. Cannot be undone from the UI.</div>' +
                 '<label class="form-label small mb-1">Payment method</label>' +
                 '<select id="pm" class="form-select form-select-sm">' +
                 '<option value="bank_transfer">Bank transfer (CRDB · 3001)</option>' +
                 '<option value="mobile_money">Mobile money (3006)</option>' +
                 '<option value="cash">Cash (3003)</option>' +
                 '</select>',
        type: 'green',
        buttons: { go: { text: 'Confirm payment', btnClass: 'btn-success', action: function() {
            document.getElementById('fPayMethod').value = document.getElementById('pm').value;
            document.getElementById('payForm').submit();
        }}, back: function(){} } });
}
function doVoid() {
    $.confirm({ title: 'Void this period?', content: '<label class="form-label small">Reason <span class="text-danger">*</span></label><textarea id="rn" class="form-control form-control-sm" rows="3"></textarea>', type: 'red',
        buttons: { go: { text: 'Void', btnClass: 'btn-danger', action: function() {
            const r = document.getElementById('rn').value.trim();
            if (!r) { $.alert('Reason required.'); return false; }
            document.getElementById('fVoidReason').value = r;
            document.getElementById('voidForm').submit();
        }}, back: function(){} } });
}
function editRecord(id, allow, otherE, otherD) {
    $.confirm({ title: 'Edit record',
        content: `
            <div class="mb-2 small text-muted">Adjust allowances / bonuses / deductions. PAYE + NSSF recompute automatically.</div>
            <label class="form-label small mb-1">Allowances (TZS)</label>
            <input type="number" step="0.01" min="0" id="ea" class="form-control form-control-sm mb-2" value="${allow}">
            <label class="form-label small mb-1">Other earnings / bonus (TZS)</label>
            <input type="number" step="0.01" min="0" id="ee" class="form-control form-control-sm mb-2" value="${otherE}">
            <label class="form-label small mb-1">Other deductions (loans, advances) (TZS)</label>
            <input type="number" step="0.01" min="0" id="ed" class="form-control form-control-sm mb-2" value="${otherD}">
            <label class="form-label small mb-1">Notes</label>
            <textarea id="en" class="form-control form-control-sm" rows="2"></textarea>
        `,
        type: 'blue',
        buttons: { go: { text: 'Save', btnClass: 'btn-primary', action: function() {
            document.getElementById('fAllow').value  = document.getElementById('ea').value;
            document.getElementById('fOtherE').value = document.getElementById('ee').value;
            document.getElementById('fOtherD').value = document.getElementById('ed').value;
            document.getElementById('fRNotes').value = document.getElementById('en').value;
            document.getElementById('recordForm').action = PROOT + 'Payroll/updateRecord/' + id;
            document.getElementById('recordForm').submit();
        }}, back: function(){} } });
}
</script>
<?php $this->end(); ?>
