<?php
require_once __DIR__ . '/../../admin/_nav.php';
require_once VIEWS . '/accountant/_nav.php';
$pageTitle  = 'Expense Management';
$_role = \Core\Session::get('user')['role'] ?? '';
$sidebarNav = $_role === 'accountant' ? accountantNav() : adminNav();
$u = function($p) { return \Core\View::url($p); };
$categories = ['salaries'=>'Salaries','utilities'=>'Utilities','supplies'=>'Supplies','maintenance'=>'Maintenance','transport'=>'Transport','meals'=>'Meals','capital'=>'Capital Expenditure','other'=>'Other'];
$catColors  = ['salaries'=>'#ef4444','utilities'=>'#f59e0b','supplies'=>'#3b82f6','maintenance'=>'#8b5cf6','transport'=>'#f59e0b','meals'=>'#10b981','capital'=>'#6b7280','other'=>'#94a3b8'];
?>
<div class="page-header">
  <div><h1><i class="bi bi-wallet2"></i> Expense Management</h1><p><?= htmlspecialchars($filters['month']) ?></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>
    <a href="<?= $u('admin/fees/voteheads') ?>" class="btn btn-secondary"><i class="bi bi-diagram-3"></i> Vote Heads</a>
    <a href="<?= $u('admin/fees/lpos') ?>" class="btn btn-secondary"><i class="bi bi-file-earmark-text"></i> LPOs</a>
    <button onclick="openModal('addExpense')" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Record Expense</button>
  </div>
</div>

<!-- Filter -->
<div class="card" style="margin-bottom:16px">
  <div class="card-body" style="padding:12px 16px">
    <form method="GET" style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
      <input type="month" name="month" value="<?= htmlspecialchars($filters['month']) ?>" style="width:160px">
      <select name="category" style="width:160px">
        <option value="">All Categories</option>
        <?php foreach($categories as $k=>$v): ?><option value="<?= $k ?>" <?= ($filters['category']??'')===$k?'selected':'' ?>><?= $v ?></option><?php endforeach; ?>
      </select>
      <button type="submit" class="btn btn-sm btn-secondary"><i class="bi bi-search"></i> Filter</button>
      <a href="<?= $u('admin/fees/expenses') ?>" class="btn btn-sm btn-secondary"><i class="bi bi-x"></i> Clear</a>
    </form>
  </div>
</div>

<!-- Monthly Summary Cards -->
<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:20px">
  <?php foreach($monthlySummary as $ms):
    $col = $catColors[$ms['category']]??'#6b7280'; ?>
  <div style="background:#fff;border:2px solid <?= $col ?>33;border-radius:10px;padding:12px 18px;min-width:140px">
    <div style="font-size:11px;color:<?= $col ?>;font-weight:700;text-transform:uppercase"><?= $categories[$ms['category']]??ucfirst($ms['category']) ?></div>
    <div style="font-size:18px;font-weight:700;margin-top:4px">KES <?= number_format($ms['total']) ?></div>
  </div>
  <?php endforeach; ?>
  <?php if($monthTotal > 0): ?>
  <div style="background:var(--primary);border-radius:10px;padding:12px 18px;min-width:140px;color:#fff">
    <div style="font-size:11px;font-weight:700;text-transform:uppercase;opacity:.8">Total</div>
    <div style="font-size:18px;font-weight:700;margin-top:4px">KES <?= number_format($monthTotal) ?></div>
  </div>
  <?php endif; ?>
</div>

<div class="card">
  <div class="card-header">
    <h5>Expense Records</h5>
    <button onclick="window.print()" class="btn btn-sm btn-secondary"><i class="bi bi-printer"></i> Print</button>
  </div>
  <div class="table-wrap"><table>
    <thead><tr><th>Date</th><th>Category</th><th>Description</th><th>Vendor</th><th>Amount</th><th>Method</th><th>Ref</th><th>Recorded By</th><th>Actions</th></tr></thead>
    <tbody>
      <?php foreach($expenses['data'] as $e):
        $col = $catColors[$e['category']]??'#6b7280'; ?>
      <tr>
        <td style="font-size:12px"><?= $e['expense_date'] ?></td>
        <td><span class="badge" style="background:<?= $col ?>22;color:<?= $col ?>"><?= $categories[$e['category']]??ucfirst($e['category']) ?></span></td>
        <td>
          <div style="font-weight:500"><?= htmlspecialchars($e['description']) ?></div>
          <?php if($e['notes']): ?><div style="font-size:11px;color:var(--gray)"><?= htmlspecialchars($e['notes']) ?></div><?php endif; ?>
        </td>
        <td style="font-size:12px"><?= htmlspecialchars($e['vendor']??'—') ?></td>
        <td><strong>KES <?= number_format($e['amount'],2) ?></strong></td>
        <td style="font-size:12px"><span class="badge badge-info"><?= strtoupper($e['payment_method']??'') ?></span></td>
        <td style="font-size:11px;color:var(--gray)"><?= htmlspecialchars($e['reference']??'—') ?></td>
        <td style="font-size:12px"><?= htmlspecialchars($e['recorded_by_name']??'—') ?></td>
        <td style="white-space:nowrap">
          <button onclick="openEditExpense(<?= htmlspecialchars(json_encode($e),ENT_QUOTES) ?>)" class="btn btn-sm btn-secondary" title="Edit"><i class="bi bi-pencil"></i></button>
          <form method="POST" action="<?= $u('admin/fees/expenses/'.$e['id'].'/delete') ?>" style="display:inline" onsubmit="return confirm('Delete this expense?')">
            <?= \Core\View::csrf() ?>
            <button type="submit" class="btn btn-sm btn-danger" title="Delete"><i class="bi bi-trash"></i></button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if(empty($expenses['data'])): ?><tr><td colspan="9" style="text-align:center;padding:40px;color:var(--gray)"><i class="bi bi-inbox" style="font-size:32px"></i><p style="margin-top:8px">No expenses for this period</p></td></tr><?php endif; ?>
    </tbody>
  </table></div>
  <div style="padding:14px"><?= \Core\View::paginate($expenses, $u('admin/fees/expenses')) ?></div>
</div>

<!-- Add Expense Modal -->
<div class="modal" id="addExpense"><div class="modal-box" style="max-width:560px">
  <div class="card-header"><h5>Record Expense</h5><button onclick="closeModal('addExpense')" 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($categories 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 - January"></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 / Supplier</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>
    <div class="form-group"><label>Notes</label><textarea name="notes" rows="2" placeholder="Additional details"></textarea></div>
    <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Record Expense</button>
  </form></div>
</div></div>

<!-- Edit Expense Modal (re-uses store with hidden _method override via separate route) -->
<div class="modal" id="editExpense"><div class="modal-box" style="max-width:560px">
  <div class="card-header"><h5>Edit Expense</h5><button onclick="closeModal('editExpense')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <div style="background:#fef3c7;border-radius:8px;padding:10px 14px;font-size:13px;margin-bottom:14px;color:#92400e">
      <i class="bi bi-info-circle"></i> To edit, delete this record and re-enter with correct details.
    </div>
    <div id="editExpenseDetails" style="font-size:13px;color:var(--gray)"></div>
    <div style="margin-top:14px;display:flex;gap:8px">
      <button onclick="closeModal('editExpense')" class="btn btn-secondary">Close</button>
    </div>
  </div>
</div></div>

<?php $expCats = json_encode($categories);
$extraScripts = '<script>
function openEditExpense(e){
  var cats='.$expCats.';
  document.getElementById("editExpenseDetails").innerHTML=
    "<strong>"+e.description+"</strong><br>"+
    "Category: "+(cats[e.category]||e.category)+" | Amount: KES "+parseFloat(e.amount).toLocaleString("en-KE",{minimumFractionDigits:2})+"<br>"+
    "Date: "+e.expense_date+" | Vendor: "+(e.vendor||"—");
  openModal("editExpense");
}
</script>'; ?>

