<?php
require_once __DIR__ . '/../../admin/_nav.php';
require_once VIEWS . '/accountant/_nav.php';
$pageTitle  = 'Aging Report — Debtors';
$_role = \Core\Session::get('user')['role'] ?? '';
$sidebarNav = $_role === 'accountant' ? accountantNav() : adminNav();
$u = function($p) { return \Core\View::url($p); };

$bucket30 = array_filter($debtors, fn($d) => $d['days_overdue'] <= 30);
$bucket60 = array_filter($debtors, fn($d) => $d['days_overdue'] > 30 && $d['days_overdue'] <= 60);
$bucket90 = array_filter($debtors, fn($d) => $d['days_overdue'] > 60);
$totalOut  = array_sum(array_column($debtors,'outstanding'));
?>
<div class="page-header">
  <div><h1><i class="bi bi-clock-history"></i> Accounts Receivable — Aging Report</h1><p>Outstanding fee balances by age</p></div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <a href="<?= $u('admin/finance') ?>" class="btn btn-secondary"><i class="bi bi-speedometer2"></i> Dashboard</a>
    <form method="GET" style="display:flex;gap:8px">
      <select name="term_id" style="width:180px">
        <option value="">All Terms</option>
        <?php foreach($terms as $t): ?><option value="<?= $t['id'] ?>" <?= $termId==$t['id']?'selected':'' ?>><?= htmlspecialchars($t['year_name'].' '.$t['name']) ?></option><?php endforeach; ?>
      </select>
      <button type="submit" class="btn btn-sm btn-secondary"><i class="bi bi-search"></i> Filter</button>
    </form>
    <?php if(!empty($debtors)): ?>
    <button onclick="window.print()" class="btn btn-secondary"><i class="bi bi-printer"></i> Print</button>
    <?php endif; ?>
  </div>
</div>

<!-- Summary Cards -->
<div class="grid g4" style="margin-bottom:20px">
  <div class="stat-card" style="">
    <div class="stat-icon si-red"><i class="bi bi-people"></i></div>
    <div class="stat-info"><h3><?= count($debtors) ?></h3><p>Total Debtors</p></div>
  </div>
  <div class="card" style="">
    <div style="font-size:11px;color:#f59e0b;font-weight:700;text-transform:uppercase">0–30 Days</div>
    <div style="font-size:22px;font-weight:700;margin:4px 0"><?= count($bucket30) ?> students</div>
    <div style="font-size:13px;color:var(--gray)">KES <?= number_format(array_sum(array_column($bucket30,'outstanding'))) ?></div>
  </div>
  <div class="card" style="">
    <div style="font-size:11px;color:#ef4444;font-weight:700;text-transform:uppercase">31–60 Days</div>
    <div style="font-size:22px;font-weight:700;margin:4px 0"><?= count($bucket60) ?> students</div>
    <div style="font-size:13px;color:var(--gray)">KES <?= number_format(array_sum(array_column($bucket60,'outstanding'))) ?></div>
  </div>
  <div class="card" style="">
    <div style="font-size:11px;color:#991b1b;font-weight:700;text-transform:uppercase">60+ Days (Critical)</div>
    <div style="font-size:22px;font-weight:700;margin:4px 0"><?= count($bucket90) ?> students</div>
    <div style="font-size:13px;color:var(--gray)">KES <?= number_format(array_sum(array_column($bucket90,'outstanding'))) ?></div>
  </div>
</div>

<!-- Aging Bar Chart -->
<?php if($totalOut > 0): ?>
<div class="card" style="margin-bottom:20px">
  <div class="card-header"><h5><i class="bi bi-bar-chart"></i> Aging Distribution</h5></div>
  <div class="card-body" style="padding:16px">
    <?php
    $agingBuckets = [
      ['0–30 Days','#f59e0b',array_sum(array_column($bucket30,'outstanding'))],
      ['31–60 Days','#ef4444',array_sum(array_column($bucket60,'outstanding'))],
      ['60+ Days','#991b1b',array_sum(array_column($bucket90,'outstanding'))],
    ];
    foreach($agingBuckets as [$lbl,$col,$amt]):
      $pct = $totalOut>0?round($amt/$totalOut*100,1):0; ?>
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:10px">
      <div style="width:90px;font-size:12px;font-weight:600;color:<?= $col ?>"><?= $lbl ?></div>
      <div style="flex:1;background:var(--light);border-radius:4px;height:22px;position:relative">
        <div style="width:<?= $pct ?>%;height:100%;background:<?= $col ?>;border-radius:4px;display:flex;align-items:center;padding-left:8px">
          <?php if($pct>10): ?><span style="font-size:11px;color:#fff;font-weight:600">KES <?= number_format($amt) ?></span><?php endif; ?>
        </div>
      </div>
      <div style="width:50px;font-size:12px;text-align:right;font-weight:600"><?= $pct ?>%</div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<?php
$buckets = [
  ['label'=>'0–30 Days','color'=>'#f59e0b','data'=>$bucket30],
  ['label'=>'31–60 Days','color'=>'#ef4444','data'=>$bucket60],
  ['label'=>'60+ Days (Critical)','color'=>'#991b1b','data'=>$bucket90],
];
foreach ($buckets as $b): if(empty($b['data'])) continue; ?>
<div class="card" style="margin-bottom:20px;border-top:3px solid <?= $b['color'] ?>">
  <div class="card-header">
    <h5 style="color:<?= $b['color'] ?>"><?= $b['label'] ?> — <?= count($b['data']) ?> students</h5>
    <span style="font-weight:700;color:<?= $b['color'] ?>">KES <?= number_format(array_sum(array_column($b['data'],'outstanding'))) ?></span>
  </div>
  <div class="table-wrap"><table>
    <thead><tr><th>Student</th><th>Class</th><th>Term</th><th>Invoice</th><th>Paid</th><th>Balance</th><th>Days Overdue</th><th>Action</th></tr></thead>
    <tbody>
      <?php foreach($b['data'] as $d): ?>
      <tr>
        <td><div style="font-weight:500"><?= htmlspecialchars($d['student_name']) ?></div><div style="font-size:11px;color:var(--gray)"><?= $d['assessment_no'] ?></div></td>
        <td style="font-size:12px"><?= htmlspecialchars(($d['class_name']??'').' '.($d['stream_name']??'')) ?></td>
        <td style="font-size:12px"><?= htmlspecialchars($d['term_name']) ?></td>
        <td>KES <?= number_format($d['total_amount'],2) ?></td>
        <td>KES <?= number_format($d['amount_paid'],2) ?></td>
        <td style="font-weight:700;color:<?= $b['color'] ?>">KES <?= number_format($d['outstanding'],2) ?></td>
        <td><span class="badge" style="background:<?= $b['color'] ?>22;color:<?= $b['color'] ?>"><?= $d['days_overdue'] ?> days</span></td>
        <td style="white-space:nowrap">
          <button onclick="openPayModal(<?= $d['id'] ?>, <?= $d['outstanding'] ?>, '<?= htmlspecialchars($d['student_name']) ?>')" class="btn btn-sm btn-primary"><i class="bi bi-plus"></i> Pay</button>
          <a href="<?= $u('admin/fees/invoice/'.$d['id'].'/history') ?>" class="btn btn-sm btn-secondary" title="History"><i class="bi bi-clock-history"></i></a>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table></div>
</div>
<?php endforeach; ?>

<?php if(empty($debtors)): ?>
<div class="card"><div class="card-body" style="text-align:center;padding:60px;color:var(--gray)">
  <i class="bi bi-check-circle" style="font-size:48px;color:var(--success)"></i>
  <p style="margin-top:12px;font-size:16px;font-weight:600">All fees are paid!</p>
  <p style="font-size:13px">No outstanding balances for the selected period.</p>
</div></div>
<?php endif; ?>

<!-- Pay Modal -->
<div class="modal" id="payModal"><div class="modal-box">
  <div class="card-header"><h5>Record Payment</h5><button onclick="closeModal('payModal')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body"><form method="POST" action="<?= $u('admin/fees/payment') ?>">
    <?= \Core\View::csrf() ?>
    <input type="hidden" name="invoice_id" id="payInvoiceId">
    <div style="background:var(--light);border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:13px">
      <div id="payStudentName" style="font-weight:600;margin-bottom:2px"></div>
      Outstanding: <strong id="payBalance" style="color:var(--danger)">—</strong>
    </div>
    <div class="grid g2">
      <div class="form-group"><label>Amount (KES) *</label><input type="number" name="amount" id="payAmount" min="1" step="0.01" required></div>
      <div class="form-group"><label>Payment Date *</label><input type="date" name="payment_date" value="<?= date('Y-m-d') ?>" required></div>
      <div class="form-group"><label>Method *</label>
        <select name="method" required>
          <option value="cash">Cash</option><option value="mpesa">M-PESA</option>
          <option value="bank">Bank</option><option value="cheque">Cheque</option>
        </select>
      </div>
      <div class="form-group"><label>Transaction Ref</label><input type="text" name="transaction_ref"></div>
    </div>
    <div class="form-group"><label>Notes</label><input type="text" name="notes"></div>
    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle"></i> Record Payment</button>
  </form></div>
</div></div>

<?php $extraScripts = '<script>
function openPayModal(id,bal,name){
  document.getElementById("payInvoiceId").value=id;
  document.getElementById("payAmount").value=bal>0?parseFloat(bal).toFixed(2):"";
  document.getElementById("payBalance").textContent="KES "+parseFloat(bal).toLocaleString("en-KE",{minimumFractionDigits:2});
  document.getElementById("payStudentName").textContent=name||"";
  openModal("payModal");
}
</script>'; ?>


