<?php
require_once __DIR__ . '/_nav.php';
$pageTitle  = 'Accountant Dashboard';
$sidebarNav = accountantNav();
$u = function($p) { return \Core\View::url($p); };

$hour  = (int)date('H');
$greet = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
$user  = \Core\Session::get('user');

$feeChart = array_fill(1, 12, 0);
foreach ($feeByMonth as $row) $feeChart[(int)$row['month']] = (float)$row['total'];
$feeJson = json_encode(array_values($feeChart));
?>

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:22px;font-weight:700"><?= $greet ?>, <?= htmlspecialchars(explode(' ', $user['name'] ?? '')[0]) ?> 👋</h1>
    <p style="color:var(--gray);font-size:13px;margin-top:2px"><i class="bi bi-calendar3"></i> <?= date('l, d F Y') ?></p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <a href="<?= $u('admin/fees/invoices') ?>" class="btn btn-primary"><i class="bi bi-receipt"></i> Invoices</a>
    <a href="<?= $u('admin/fees/expenses') ?>" class="btn btn-secondary"><i class="bi bi-wallet2"></i> Expenses</a>
    <a href="<?= $u('admin/fees/reports') ?>" class="btn btn-secondary"><i class="bi bi-bar-chart"></i> Reports</a>
  </div>
</div>

<!-- Quick Actions -->
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:24px">
  <button onclick="openModal('recordPayModal')" class="btn btn-primary btn-sm"><i class="bi bi-plus-circle"></i> Record Payment</button>
  <a href="<?= $u('admin/fees/invoices') ?>" class="btn btn-secondary btn-sm"><i class="bi bi-receipt"></i> Invoices</a>
  <a href="<?= $u('admin/fees/invoices?status=unpaid') ?>" class="btn btn-secondary btn-sm"><i class="bi bi-exclamation-circle"></i> Unpaid</a>
  <a href="<?= $u('admin/fees/aging') ?>" class="btn btn-secondary btn-sm"><i class="bi bi-clock-history"></i> Debtors</a>
  <button onclick="openModal('addExpenseModal')" class="btn btn-secondary btn-sm"><i class="bi bi-wallet2"></i> Add Expense</button>
  <a href="<?= $u('admin/fees/reports') ?>" class="btn btn-secondary btn-sm"><i class="bi bi-bar-chart"></i> Reports</a>
  <a href="<?= $u('admin/fees/cashbook') ?>" class="btn btn-secondary btn-sm"><i class="bi bi-journal-text"></i> Cashbook</a>
  <a href="<?= $u('admin/fees/balancesheet') ?>" class="btn btn-secondary btn-sm"><i class="bi bi-journal-bookmark"></i> Balance Sheet</a>
</div>

<!-- Record Payment Modal -->
<div class="modal" id="recordPayModal"><div class="modal-box" style="max-width:540px">
  <div class="card-header"><h5><i class="bi bi-cash"></i> Record Payment</h5><button onclick="closeModal('recordPayModal')" 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() ?>

      <div class="form-group">
        <label>Select Student *</label>
        <input type="text" id="rp_search" placeholder="Type to filter students..." autocomplete="off" oninput="filterSelect(this.value)" style="margin-bottom:6px">
        <select name="invoice_id" id="rp_select" required onchange="showInvoiceInfo(this.value)" size="5" style="height:auto">
          <option value="">-- Select Student --</option>
          <?php foreach($studentsWithInvoices as $si): ?>
          <option value="<?= $si['invoice_id'] ?>"
            data-total="<?= $si['total_amount'] ?>"
            data-paid="<?= $si['amount_paid'] ?>"
            data-balance="<?= $si['outstanding'] ?>"
            data-term="<?= htmlspecialchars($si['term_name']) ?>"
            data-label="<?= htmlspecialchars(strtolower($si['student_name'].' '.$si['assessment_no'])) ?>">
            <?= htmlspecialchars($si['student_name']) ?> (<?= htmlspecialchars($si['assessment_no']) ?>) — KES <?= number_format($si['outstanding'],2) ?>
          </option>
          <?php endforeach; ?>
        </select>
        <small style="color:var(--gray)"><?= count($studentsWithInvoices) ?> students with outstanding balances</small>
      </div>

      <!-- Invoice info -->
      <div id="rp_student_info" style="display:none;background:var(--light);border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:13px">
        <div style="display:flex;gap:16px">
          <span>Invoice: <strong id="rp_total"></strong></span>
          <span>Paid: <strong id="rp_paid" style="color:var(--success)"></strong></span>
          <span>Balance: <strong id="rp_balance" style="color:var(--danger)"></strong></span>
        </div>
        <div style="font-size:12px;color:var(--gray);margin-top:4px" id="rp_term"></div>
      </div>

      <div class="grid g2">
        <div class="form-group"><label>Amount (KES) *</label><input type="number" name="amount" id="rp_amount" 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 Transfer</option>
            <option value="cheque">Cheque</option>
            <option value="rtgs">RTGS</option>
          </select>
        </div>
        <div class="form-group"><label>Transaction Reference</label><input type="text" name="transaction_ref" placeholder="MPESA code / Cheque no"></div>
      </div>
      <div class="form-group"><label>Notes</label><input type="text" name="notes" placeholder="Optional"></div>
      <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle"></i> Record Payment</button>
    </form>
  </div>
</div></div>

<!-- Add Expense Modal -->
<div class="modal" id="addExpenseModal"><div class="modal-box" style="max-width:520px">
  <div class="card-header"><h5><i class="bi bi-wallet2"></i> Record Expense</h5><button onclick="closeModal('addExpenseModal')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <form method="POST" action="<?= $u('admin/fees/expenses/store') ?>">
      <?= \Core\View::csrf() ?>
      <div class="grid g2">
        <div class="form-group"><label>Category *</label>
          <select name="category" required>
            <?php foreach(['salaries'=>'Salaries','utilities'=>'Utilities','supplies'=>'Supplies','maintenance'=>'Maintenance','transport'=>'Transport','meals'=>'Meals','capital'=>'Capital','other'=>'Other'] as $k=>$v): ?>
            <option value="<?= $k ?>"><?= $v ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group"><label>Date *</label><input type="date" name="expense_date" value="<?= date('Y-m-d') ?>" required></div>
        <div class="form-group" style="grid-column:span 2"><label>Description *</label><input type="text" name="description" required placeholder="e.g. Electricity bill"></div>
        <div class="form-group"><label>Amount (KES) *</label><input type="number" name="amount" min="0" step="0.01" required></div>
        <div class="form-group"><label>Payment Method</label>
          <select name="payment_method">
            <option value="cash">Cash</option><option value="bank">Bank</option>
            <option value="mpesa">M-PESA</option><option value="cheque">Cheque</option>
          </select>
        </div>
        <div class="form-group"><label>Vendor</label><input type="text" name="vendor" placeholder="e.g. Kenya Power"></div>
        <div class="form-group"><label>Reference No.</label><input type="text" name="reference" placeholder="Invoice / receipt no."></div>
      </div>
      <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Record Expense</button>
    </form>
  </div>
</div></div>

<!-- KPI Cards -->
<div class="grid g4" style="margin-bottom:20px">
  <div class="stat-card" style="">
    <div class="stat-icon si-blue"><i class="bi bi-cash-stack"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($expected) ?></h3><p>Expected (Current Term)</p></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-green"><i class="bi bi-check-circle"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($collected) ?></h3><p>Collected (<?= $feeRate ?>%)</p></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-red"><i class="bi bi-exclamation-circle"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($outstanding) ?></h3><p>Outstanding</p></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-amber"><i class="bi bi-wallet2"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($expenseMonth['total'] ?? 0) ?></h3><p>Expenses This Month</p></div>
  </div>
</div>

<!-- Invoice status pills -->
<div class="grid g3" style="margin-bottom:20px">
  <div class="stat-card" style="">
    <div class="stat-icon si-green"><i class="bi bi-check2-all"></i></div>
    <div class="stat-info"><h3><?= $summary['paid_count'] ?? 0 ?></h3><p>Fully Paid Invoices</p></div>
    <div style="margin-left:auto"><a href="<?= $u('admin/fees/invoices?status=paid') ?>" class="btn btn-sm btn-secondary">View</a></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-amber"><i class="bi bi-hourglass-split"></i></div>
    <div class="stat-info"><h3><?= $summary['partial_count'] ?? 0 ?></h3><p>Partial Payments</p></div>
    <div style="margin-left:auto"><a href="<?= $u('admin/fees/invoices?status=partial') ?>" class="btn btn-sm btn-secondary">View</a></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-red"><i class="bi bi-x-circle"></i></div>
    <div class="stat-info"><h3><?= $summary['unpaid_count'] ?? 0 ?></h3><p>Unpaid Invoices</p></div>
    <div style="margin-left:auto"><a href="<?= $u('admin/fees/invoices?status=unpaid') ?>" class="btn btn-sm btn-secondary">View</a></div>
  </div>
</div>

<!-- Collection rate bar -->
<div class="card" style="margin-bottom:20px">
  <div class="card-body" style="padding:14px 18px">
    <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px">
      <span style="font-weight:600">Overall Collection Rate</span>
      <span style="font-weight:700;color:<?= $feeRate>=80?'var(--success)':($feeRate>=50?'var(--warning)':'var(--danger)') ?>"><?= $feeRate ?>%</span>
    </div>
    <div style="background:var(--light);border-radius:8px;height:12px">
      <div style="width:<?= min(100,$feeRate) ?>%;background:<?= $feeRate>=80?'var(--success)':($feeRate>=50?'var(--warning)':'var(--danger)') ?>;height:12px;border-radius:8px"></div>
    </div>
  </div>
</div>

<div class="grid g2" style="margin-bottom:20px">
  <!-- Fee collection chart -->
  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-bar-chart-line"></i> Fee Collection <?= date('Y') ?></h5>
      <a href="<?= $u('admin/fees/reports') ?>" class="btn btn-sm btn-secondary">Full Report</a>
    </div>
    <div class="card-body"><canvas id="feeChart" height="200"></canvas></div>
  </div>

  <!-- Collection by class -->
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-table"></i> Collection by Class</h5></div>
    <div class="card-body" style="padding:0">
      <?php if(empty($byClass)): ?>
      <div style="padding:30px;text-align:center;color:var(--gray)">No data yet</div>
      <?php else: ?>
      <?php foreach($byClass as $cl):
        $rate = $cl['expected'] > 0 ? round($cl['collected']/$cl['expected']*100,1) : 0; ?>
      <div style="padding:10px 18px;border-bottom:1px solid var(--border)">
        <div style="display:flex;justify-content:space-between;margin-bottom:4px;font-size:13px">
          <span style="font-weight:500"><?= htmlspecialchars($cl['class_name'] ?? 'Unknown') ?></span>
          <span style="color:<?= $rate>=80?'var(--success)':($rate>=50?'var(--warning)':'var(--danger)') ?>;font-weight:600"><?= $rate ?>%</span>
        </div>
        <div style="background:var(--light);border-radius:4px;height:6px">
          <div style="width:<?= min(100,$rate) ?>%;background:<?= $rate>=80?'var(--success)':($rate>=50?'var(--warning)':'var(--danger)') ?>;height:6px;border-radius:4px"></div>
        </div>
        <div style="font-size:11px;color:var(--gray);margin-top:3px">KES <?= number_format($cl['collected']) ?> / <?= number_format($cl['expected']) ?></div>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Recent Payments -->
<div class="card">
  <div class="card-header">
    <h5><i class="bi bi-credit-card"></i> Recent Payments</h5>
    <a href="<?= $u('admin/fees/invoices') ?>" class="btn btn-sm btn-secondary">View All</a>
  </div>
  <div class="card-body" style="padding:0">
    <?php if(empty($recentPayments)): ?>
    <div style="padding:30px;text-align:center;color:var(--gray)"><i class="bi bi-inbox" style="font-size:32px;display:block;margin-bottom:8px"></i>No payments yet</div>
    <?php else: ?>
    <?php foreach($recentPayments as $p): ?>
    <div style="padding:12px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px">
      <div class="stat-icon si-green" style="width:36px;height:36px;font-size:14px;border-radius:8px;flex-shrink:0">
        <i class="bi bi-<?= $p['method']==='mpesa'?'phone':'cash' ?>"></i>
      </div>
      <div style="flex:1">
        <div style="font-weight:500;font-size:13px"><?= htmlspecialchars($p['student_name']) ?></div>
        <div style="font-size:11px;color:var(--gray)"><?= ucfirst($p['method']) ?> &bull; <?= $p['payment_date'] ?></div>
      </div>
      <div style="font-weight:700;color:var(--success)">KES <?= number_format($p['amount']) ?></div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

<?php
$invoicesJson = json_encode($studentsWithInvoices);
$extraScripts = '<script src="/cbe/sms/public/assets/chart.min.js"></script><script>Chart.defaults.font.family="Inter,sans-serif";Chart.defaults.font.size=12;new Chart("feeChart",{type:"bar",data:{labels:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],datasets:[{label:"KES",data:'.$feeJson.',backgroundColor:"rgba(26,127,90,.75)",borderRadius:6}]},options:{responsive:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{callback:function(v){return"KES "+v.toLocaleString();}}},x:{grid:{display:false}}}}});</script>';
?>
<script>
function filterSelect(q) {
    var sel = document.getElementById('rp_select');
    var opts = sel.querySelectorAll('option');
    q = q.trim().toLowerCase();
    opts.forEach(function(opt) {
        if (!opt.value) return;
        var match = !q || opt.dataset.label.indexOf(q) >= 0;
        opt.hidden = !match;
        opt.disabled = !match;
    });
    if (sel.selectedOptions[0] && sel.selectedOptions[0].hidden) {
        sel.value = '';
        document.getElementById('rp_student_info').style.display = 'none';
    }
}
function showInvoiceInfo(val) {
    var info = document.getElementById('rp_student_info');
    if (!val) { info.style.display = 'none'; return; }
    var sel = document.querySelector('select[name="invoice_id"] option[value="' + val + '"]');
    if (!sel) { info.style.display = 'none'; return; }
    document.getElementById('rp_total').textContent   = 'KES ' + parseFloat(sel.dataset.total).toLocaleString('en-KE', {minimumFractionDigits:2});
    document.getElementById('rp_paid').textContent    = 'KES ' + parseFloat(sel.dataset.paid).toLocaleString('en-KE', {minimumFractionDigits:2});
    document.getElementById('rp_balance').textContent = 'KES ' + parseFloat(sel.dataset.balance).toLocaleString('en-KE', {minimumFractionDigits:2});
    document.getElementById('rp_term').textContent    = sel.dataset.term;
    document.getElementById('rp_amount').value        = parseFloat(sel.dataset.balance).toFixed(2);
    info.style.display = 'block';
}
</script>
