<?php
require_once __DIR__ . '/../../admin/_nav.php';
require_once VIEWS . '/accountant/_nav.php';
$pageTitle  = 'Cash Flow Statement';
$_role = \Core\Session::get('user')['role'] ?? '';
$sidebarNav = $_role === 'accountant' ? accountantNav() : adminNav();
$u = function($p) { return \Core\View::url($p); };
$netFlow = $totalInflow - $totalOutflow;
?>
<div class="page-header">
  <div><h1><i class="bi bi-arrow-left-right"></i> Cash Flow Statement</h1><p>Annual inflows vs outflows</p></div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <a href="<?= $u('admin/fees/reports') ?>" class="btn btn-secondary"><i class="bi bi-bar-chart"></i> Reports</a>
    <a href="<?= $u('admin/fees/balancesheet') ?>" class="btn btn-secondary"><i class="bi bi-journal-bookmark"></i> Balance Sheet</a>
    <form method="GET" style="display:flex;gap:6px">
      <select name="year" onchange="this.form.submit()" style="width:120px">
        <?php foreach($years as $y): ?><option value="<?= $y ?>" <?= $year==$y?'selected':'' ?>><?= $y ?></option><?php endforeach; ?>
      </select>
    </form>
    <button onclick="window.print()" class="btn btn-secondary"><i class="bi bi-printer"></i> Print</button>
  </div>
</div>

<!-- Summary -->
<div class="grid g3" style="margin-bottom:24px">
  <div class="card" style="border-top:4px solid var(--success)">
    <div class="card-body" style="padding:20px;text-align:center">
      <div style="font-size:12px;color:var(--gray);text-transform:uppercase;font-weight:600">Total Inflows <?= $year ?></div>
      <div style="font-size:28px;font-weight:700;color:var(--success);margin:8px 0">KES <?= number_format($totalInflow) ?></div>
      <div style="font-size:12px;color:var(--gray)">Fee collections</div>
    </div>
  </div>
  <div class="card" style="border-top:4px solid var(--danger)">
    <div class="card-body" style="padding:20px;text-align:center">
      <div style="font-size:12px;color:var(--gray);text-transform:uppercase;font-weight:600">Total Outflows <?= $year ?></div>
      <div style="font-size:28px;font-weight:700;color:var(--danger);margin:8px 0">KES <?= number_format($totalOutflow) ?></div>
      <div style="font-size:12px;color:var(--gray)">All expenses</div>
    </div>
  </div>
  <div class="card" style="border-top:4px solid <?= $netFlow>=0?'var(--success)':'var(--danger)' ?>">
    <div class="card-body" style="padding:20px;text-align:center">
      <div style="font-size:12px;color:var(--gray);text-transform:uppercase;font-weight:600">Net Cash Flow</div>
      <div style="font-size:28px;font-weight:700;color:<?= $netFlow>=0?'var(--success)':'var(--danger)' ?>;margin:8px 0">KES <?= number_format(abs($netFlow)) ?></div>
      <div style="font-size:13px;font-weight:600;color:<?= $netFlow>=0?'var(--success)':'var(--danger)' ?>"><?= $netFlow>=0?'Net Positive':'Net Negative' ?></div>
    </div>
  </div>
</div>

<!-- Monthly Cash Flow Table -->
<div class="card" style="margin-bottom:24px">
  <div class="card-header"><h5><i class="bi bi-table"></i> Monthly Cash Flow — <?= $year ?></h5></div>
  <div class="table-wrap"><table>
    <thead><tr><th>Month</th><th>Inflows (Fees)</th><th>Outflows (Expenses)</th><th>Net Flow</th><th>Cumulative</th></tr></thead>
    <tbody>
      <?php
      $cumulative = 0;
      $allMonths = [];
      for($m=1;$m<=12;$m++) $allMonths[$year.'-'.str_pad($m,2,'0',STR_PAD_LEFT)] = ['inflow'=>0,'outflow'=>0];
      foreach($months as $k=>$v) $allMonths[$k] = array_merge($allMonths[$k]??[], $v);
      foreach($allMonths as $mon => $data):
        $inflow  = (float)($data['inflow']??0);
        $outflow = (float)($data['outflow']??0);
        $net     = $inflow - $outflow;
        $cumulative += $net;
        $hasData = $inflow>0 || $outflow>0;
      ?>
      <tr style="<?= !$hasData?'opacity:.4':'' ?>">
        <td style="font-weight:500"><?= date('F Y', strtotime($mon.'-01')) ?></td>
        <td style="color:var(--success);font-weight:<?= $inflow>0?'600':'400' ?>"><?= $inflow>0?'KES '.number_format($inflow,2):'—' ?></td>
        <td style="color:var(--danger);font-weight:<?= $outflow>0?'600':'400' ?>"><?= $outflow>0?'KES '.number_format($outflow,2):'—' ?></td>
        <td style="font-weight:600;color:<?= $net>=0?'var(--success)':'var(--danger)' ?>"><?= $hasData?($net>=0?'+':'').'KES '.number_format($net,2):'—' ?></td>
        <td style="font-weight:600;color:<?= $cumulative>=0?'var(--success)':'var(--danger)' ?>"><?= $hasData?'KES '.number_format($cumulative,2):'—' ?></td>
      </tr>
      <?php endforeach; ?>
    </tbody>
    <tfoot>
      <tr style="background:var(--light);font-weight:700">
        <td>TOTAL</td>
        <td style="color:var(--success)">KES <?= number_format($totalInflow,2) ?></td>
        <td style="color:var(--danger)">KES <?= number_format($totalOutflow,2) ?></td>
        <td style="color:<?= $netFlow>=0?'var(--success)':'var(--danger)' ?>"><?= $netFlow>=0?'+':'' ?>KES <?= number_format($netFlow,2) ?></td>
        <td>—</td>
      </tr>
    </tfoot>
  </table></div>
</div>

<!-- Expense Breakdown by Category -->
<?php if(!empty($expByCategory)): ?>
<div class="card">
  <div class="card-header"><h5><i class="bi bi-pie-chart"></i> Expense Breakdown by Category — <?= $year ?></h5></div>
  <div class="card-body" style="padding:16px">
    <?php
    $catColors = ['salaries'=>'#ef4444','utilities'=>'#f59e0b','supplies'=>'#3b82f6','maintenance'=>'#8b5cf6','transport'=>'#f59e0b','meals'=>'#10b981','capital'=>'#6b7280','other'=>'#94a3b8'];
    $catLabels = ['salaries'=>'Salaries','utilities'=>'Utilities','supplies'=>'Supplies','maintenance'=>'Maintenance','transport'=>'Transport','meals'=>'Meals','capital'=>'Capital','other'=>'Other'];
    foreach($expByCategory as $ec):
      $pct = $totalOutflow>0?round($ec['total']/$totalOutflow*100,1):0;
      $col = $catColors[$ec['category']]??'#6b7280'; ?>
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:10px">
      <div style="width:100px;font-size:12px;font-weight:600;color:<?= $col ?>;text-transform:capitalize"><?= $catLabels[$ec['category']]??ucfirst($ec['category']) ?></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>8): ?><span style="font-size:11px;color:#fff;font-weight:600">KES <?= number_format($ec['total']) ?></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; ?>

