<?php
require_once __DIR__ . '/../../admin/_nav.php';
require_once VIEWS . '/accountant/_nav.php';
$pageTitle  = 'Financial Reports';
$_role = \Core\Session::get('user')['role'] ?? '';
$sidebarNav = $_role === 'accountant' ? accountantNav() : adminNav();
$u = function($p) { return \Core\View::url($p); };
$catColors = ['tuition'=>'#3b82f6','transport'=>'#f59e0b','boarding'=>'#8b5cf6','meals'=>'#10b981','activity'=>'#ef4444','other'=>'#6b7280'];
$net = $yearIncome - $yearExpense;
?>
<div class="page-header">
  <div><h1><i class="bi bi-bar-chart-line"></i> Financial Reports</h1></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>
    <a href="<?= $u('admin/fees/cashflow') ?>" class="btn btn-secondary"><i class="bi bi-arrow-left-right"></i> Cash Flow</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: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">Apply</button>
    </form>
    <button onclick="window.print()" class="btn btn-secondary"><i class="bi bi-printer"></i> Print</button>
  </div>
</div>

<!-- Income vs Expense 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;letter-spacing:.5px">Fee Income (This Year)</div>
      <div style="font-size:30px;font-weight:700;color:var(--success);margin:10px 0">KES <?= number_format($yearIncome) ?></div>
      <div style="font-size:12px;color:var(--gray)">Total collected from students</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;letter-spacing:.5px">Total Expenses (This Year)</div>
      <div style="font-size:30px;font-weight:700;color:var(--danger);margin:10px 0">KES <?= number_format($yearExpense) ?></div>
      <div style="font-size:12px;color:var(--gray)">All recorded expenditures</div>
    </div>
  </div>
  <div class="card" style="border-top:4px solid <?= $net>=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;letter-spacing:.5px">Net Position</div>
      <div style="font-size:30px;font-weight:700;color:<?= $net>=0?'var(--success)':'var(--danger)' ?>;margin:10px 0">KES <?= number_format(abs($net)) ?></div>
      <div style="font-size:13px;font-weight:600;color:<?= $net>=0?'var(--success)':'var(--danger)' ?>"><?= $net>=0?'✅ Surplus':'⚠️ Deficit' ?></div>
    </div>
  </div>
</div>

<!-- Monthly Trend -->
<?php if(!empty($trend)): ?>
<div class="card" style="margin-bottom:24px">
  <div class="card-header"><h5><i class="bi bi-graph-up"></i> Monthly Collection Trend (Last 6 Months)</h5></div>
  <div class="card-body" style="padding:16px">
    <?php
    $maxTrend = max(array_column($trend,'collected') ?: [1]);
    foreach ($trend as $tr):
      $pct = round($tr['collected']/$maxTrend*100); ?>
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:10px">
      <div style="width:70px;font-size:12px;color:var(--gray);text-align:right"><?= $tr['month'] ?></div>
      <div style="flex:1;background:var(--light);border-radius:4px;height:26px;position:relative">
        <div style="width:<?= $pct ?>%;height:100%;background:var(--primary);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($tr['collected']) ?></span><?php endif; ?>
        </div>
        <?php if($pct<=8): ?><span style="position:absolute;left:calc(<?= $pct ?>% + 8px);top:50%;transform:translateY(-50%);font-size:11px;font-weight:600">KES <?= number_format($tr['collected']) ?></span><?php endif; ?>
      </div>
      <div style="width:80px;font-size:11px;color:var(--gray)"><?= $tr['transactions'] ?> payments</div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<!-- Collection by Class -->
<div class="card" style="margin-bottom:24px">
  <div class="card-header"><h5><i class="bi bi-building"></i> Fee Collection by Class</h5></div>
  <div class="table-wrap"><table>
    <thead><tr><th>Class</th><th>Students</th><th>Expected</th><th>Collected</th><th>Balance</th><th>Collection Rate</th></tr></thead>
    <tbody>
      <?php
      $grandExp = array_sum(array_column($byClass,'expected'));
      $grandCol = array_sum(array_column($byClass,'collected'));
      foreach($byClass as $c):
        $rate = $c['expected']>0?round($c['collected']/$c['expected']*100,1):0; ?>
      <tr>
        <td><strong><?= htmlspecialchars($c['class_name']??'Unknown') ?></strong></td>
        <td><?= $c['students'] ?></td>
        <td>KES <?= number_format($c['expected']) ?></td>
        <td>KES <?= number_format($c['collected']) ?></td>
        <td style="color:<?= $c['balance']>0?'var(--danger)':'var(--success)' ?>">KES <?= number_format($c['balance']) ?></td>
        <td style="min-width:140px">
          <div style="display:flex;align-items:center;gap:8px">
            <div style="flex:1;background:var(--light);border-radius:4px;height:10px">
              <div style="width:<?= $rate ?>%;height:100%;background:<?= $rate>=80?'var(--success)':($rate>=50?'#f59e0b':'var(--danger)') ?>;border-radius:4px"></div>
            </div>
            <span style="font-size:12px;font-weight:700;min-width:40px"><?= $rate ?>%</span>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if(!empty($byClass)): ?>
      <tr style="background:var(--light);font-weight:700">
        <td>TOTAL</td><td>—</td>
        <td>KES <?= number_format($grandExp) ?></td>
        <td>KES <?= number_format($grandCol) ?></td>
        <td style="color:<?= ($grandExp-$grandCol)>0?'var(--danger)':'var(--success)' ?>">KES <?= number_format($grandExp-$grandCol) ?></td>
        <td><?= $grandExp>0?round($grandCol/$grandExp*100,1):0 ?>%</td>
      </tr>
      <?php endif; ?>
      <?php if(empty($byClass)): ?><tr><td colspan="6" style="text-align:center;padding:30px;color:var(--gray)">No data</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>

<!-- Fee Category Breakdown -->
<?php if(!empty($byCategory)): ?>
<div class="card" style="margin-bottom:24px">
  <div class="card-header"><h5><i class="bi bi-tags"></i> Expected Revenue by Fee Category</h5></div>
  <div class="card-body" style="padding:16px">
    <div style="display:flex;gap:12px;flex-wrap:wrap">
      <?php foreach($byCategory as $bc):
        $col = $catColors[$bc['category']]??'#6b7280'; ?>
      <div style="background:<?= $col ?>15;border:2px solid <?= $col ?>33;border-radius:10px;padding:14px 20px;min-width:150px;text-align:center">
        <div style="font-size:11px;color:<?= $col ?>;font-weight:700;text-transform:uppercase"><?= ucfirst($bc['category']) ?></div>
        <div style="font-size:20px;font-weight:700;margin:6px 0">KES <?= number_format($bc['expected']) ?></div>
        <div style="font-size:11px;color:var(--gray)"><?= $bc['students'] ?> students</div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- Quick Links to Other Reports -->
<div class="grid g3">
  <a href="<?= $u('admin/fees/cashflow') ?>" style="text-decoration:none">
    <div class="card" style="" onmouseover="this.style.boxShadow='0 4px 12px rgba(0,0,0,.1)'" onmouseout="this.style.boxShadow=''">
      <div class="card-body" style="padding:20px">
        <div style="font-size:24px;color:#3b82f6;margin-bottom:8px"><i class="bi bi-arrow-left-right"></i></div>
        <div style="font-weight:600;font-size:15px">Cash Flow Statement</div>
        <div style="font-size:12px;color:var(--gray);margin-top:4px">Monthly inflows vs outflows</div>
      </div>
    </div>
  </a>
  <a href="<?= $u('admin/fees/balancesheet') ?>" style="text-decoration:none">
    <div class="card" style="" onmouseover="this.style.boxShadow='0 4px 12px rgba(0,0,0,.1)'" onmouseout="this.style.boxShadow=''">
      <div class="card-body" style="padding:20px">
        <div style="font-size:24px;color:var(--success);margin-bottom:8px"><i class="bi bi-journal-bookmark"></i></div>
        <div style="font-weight:600;font-size:15px">Balance Sheet</div>
        <div style="font-size:12px;color:var(--gray);margin-top:4px">Assets, liabilities & surplus</div>
      </div>
    </div>
  </a>
  <a href="<?= $u('admin/fees/aging') ?>" style="text-decoration:none">
    <div class="card" style="" onmouseover="this.style.boxShadow='0 4px 12px rgba(0,0,0,.1)'" onmouseout="this.style.boxShadow=''">
      <div class="card-body" style="padding:20px">
        <div style="font-size:24px;color:var(--danger);margin-bottom:8px"><i class="bi bi-clock-history"></i></div>
        <div style="font-weight:600;font-size:15px">Aging / Debtors Report</div>
        <div style="font-size:12px;color:var(--gray);margin-top:4px">Outstanding balances by age</div>
      </div>
    </div>
  </a>
</div>

