<?php
require_once __DIR__ . '/../../admin/_nav.php';
require_once VIEWS . '/accountant/_nav.php';
$pageTitle  = 'Vote Heads';
$_role = \Core\Session::get('user')['role'] ?? '';
$sidebarNav = $_role === 'accountant' ? accountantNav() : adminNav();
$u = function($p) { return \Core\View::url($p); };
$catColors = ['income'=>'#10b981','recurrent'=>'#3b82f6','development'=>'#8b5cf6','other'=>'#6b7280'];
$catLabels = ['income'=>'Income','recurrent'=>'Recurrent','development'=>'Development','other'=>'Other'];

$totalBudget = array_sum(array_column($voteHeads,'budget_amount'));
$totalSpent  = array_sum(array_column($voteHeads,'spent'));
$totalVar    = $totalBudget - $totalSpent;
?>
<div class="page-header">
  <div><h1><i class="bi bi-diagram-3"></i> Vote Heads</h1><p>Budget lines & expenditure tracking</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:6px">
      <select name="year_id" onchange="this.form.submit()" style="width:160px">
        <?php foreach($years as $y): ?><option value="<?= $y['id'] ?>" <?= $yearId==$y['id']?'selected':'' ?>><?= htmlspecialchars($y['name']) ?></option><?php endforeach; ?>
      </select>
    </form>
    <button onclick="openModal('addVH')" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Vote Head</button>
  </div>
</div>

<!-- Summary -->
<div class="grid g3" style="margin-bottom:20px">
  <div class="stat-card" style="">
    <div class="stat-icon si-blue"><i class="bi bi-diagram-3"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($totalBudget) ?></h3><p>Total Budget</p></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-red"><i class="bi bi-wallet2"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($totalSpent) ?></h3><p>Total Spent</p></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon <?= $totalVar>=0?'si-green':'si-red' ?>"><i class="bi bi-calculator"></i></div>
    <div class="stat-info"><h3 style="color:<?= $totalVar>=0?'var(--success)':'var(--danger)' ?>">KES <?= number_format(abs($totalVar)) ?></h3><p><?= $totalVar>=0?'Budget Remaining':'Over Budget' ?></p></div>
  </div>
</div>

<?php
$grouped = [];
foreach($voteHeads as $vh) $grouped[$vh['category']][] = $vh;
foreach($grouped as $cat => $items): ?>
<div class="card" style="margin-bottom:20px">
  <div class="card-header" style="">
    <h5 style="color:<?= $catColors[$cat]??'#6b7280' ?>"><?= $catLabels[$cat]??ucfirst($cat) ?> Vote Heads</h5>
    <span style="font-size:13px;color:var(--gray)"><?= count($items) ?> items | Budget: KES <?= number_format(array_sum(array_column($items,'budget_amount'))) ?></span>
  </div>
  <div class="table-wrap"><table>
    <thead><tr><th>Code</th><th>Name</th><th>Budget</th><th>Spent</th><th>Variance</th><th>Utilization</th><th>Actions</th></tr></thead>
    <tbody>
      <?php foreach($items as $vh):
        $util = $vh['budget_amount']>0?round($vh['spent']/$vh['budget_amount']*100,1):0;
        $var  = (float)$vh['budget_amount']-(float)$vh['spent']; ?>
      <tr>
        <td><span class="badge badge-info"><?= htmlspecialchars($vh['code']) ?></span></td>
        <td><strong><?= htmlspecialchars($vh['name']) ?></strong><?php if($vh['description']): ?><div style="font-size:11px;color:var(--gray)"><?= htmlspecialchars($vh['description']) ?></div><?php endif; ?></td>
        <td>KES <?= number_format($vh['budget_amount'],2) ?></td>
        <td>KES <?= number_format($vh['spent'],2) ?></td>
        <td style="font-weight:600;color:<?= $var>=0?'var(--success)':'var(--danger)' ?>">
          <?= $var>=0?'+':'' ?>KES <?= number_format($var,2) ?>
        </td>
        <td style="min-width:130px">
          <div style="display:flex;align-items:center;gap:6px">
            <div style="flex:1;background:var(--light);border-radius:4px;height:8px">
              <div style="width:<?= min($util,100) ?>%;height:100%;background:<?= $util>=100?'var(--danger)':($util>=80?'#f59e0b':'var(--success)') ?>;border-radius:4px"></div>
            </div>
            <span style="font-size:11px;font-weight:600;min-width:36px"><?= $util ?>%</span>
          </div>
        </td>
        <td style="white-space:nowrap">
          <button onclick="openEditVH(<?= htmlspecialchars(json_encode($vh),ENT_QUOTES) ?>)" class="btn btn-sm btn-secondary"><i class="bi bi-pencil"></i></button>
          <form method="POST" action="<?= $u('admin/fees/voteheads/'.$vh['id'].'/delete') ?>" style="display:inline" onsubmit="return confirm('Delete this vote head?')">
            <?= \Core\View::csrf() ?>
            <button type="submit" class="btn btn-sm btn-danger"><i class="bi bi-trash"></i></button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table></div>
</div>
<?php endforeach; ?>

<?php if(empty($voteHeads)): ?>
<div class="card"><div class="card-body" style="text-align:center;padding:60px;color:var(--gray)">
  <i class="bi bi-diagram-3" style="font-size:48px"></i>
  <p style="margin-top:12px">No vote heads defined. Add budget lines to track expenditure.</p>
  <button onclick="openModal('addVH')" class="btn btn-primary" style="margin-top:12px"><i class="bi bi-plus-lg"></i> Add Vote Head</button>
</div></div>
<?php endif; ?>

<!-- Add Vote Head Modal -->
<div class="modal" id="addVH"><div class="modal-box">
  <div class="card-header"><h5>Add Vote Head</h5><button onclick="closeModal('addVH')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body"><form method="POST" action="<?= $u('admin/fees/voteheads/store') ?>">
    <?= \Core\View::csrf() ?>
    <input type="hidden" name="academic_year_id" value="<?= $yearId ?>">
    <div class="grid g2">
      <div class="form-group"><label>Code *</label><input type="text" name="code" required placeholder="e.g. VH001" style="text-transform:uppercase"></div>
      <div class="form-group"><label>Category *</label>
        <select name="category" required>
          <?php foreach($catLabels as $k=>$v): ?><option value="<?= $k ?>"><?= $v ?></option><?php endforeach; ?>
        </select>
      </div>
      <div class="form-group" style="grid-column:span 2"><label>Name *</label><input type="text" name="name" required placeholder="e.g. Teacher Salaries"></div>
      <div class="form-group"><label>Budget Amount (KES) *</label><input type="number" name="budget_amount" min="0" step="0.01" required></div>
    </div>
    <div class="form-group"><label>Description</label><input type="text" name="description" placeholder="Optional details"></div>
    <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Add Vote Head</button>
  </form></div>
</div></div>

<!-- Edit Vote Head Modal -->
<div class="modal" id="editVH"><div class="modal-box">
  <div class="card-header"><h5>Edit Vote Head</h5><button onclick="closeModal('editVH')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body"><form method="POST" id="editVHForm" action="">
    <?= \Core\View::csrf() ?>
    <div class="grid g2">
      <div class="form-group"><label>Code *</label><input type="text" name="code" id="evhCode" required style="text-transform:uppercase"></div>
      <div class="form-group"><label>Category *</label>
        <select name="category" id="evhCat">
          <?php foreach($catLabels as $k=>$v): ?><option value="<?= $k ?>"><?= $v ?></option><?php endforeach; ?>
        </select>
      </div>
      <div class="form-group" style="grid-column:span 2"><label>Name *</label><input type="text" name="name" id="evhName" required></div>
      <div class="form-group"><label>Budget Amount (KES) *</label><input type="number" name="budget_amount" id="evhBudget" min="0" step="0.01" required></div>
    </div>
    <div class="form-group"><label>Description</label><input type="text" name="description" id="evhDesc"></div>
    <button type="submit" class="btn btn-primary">Update Vote Head</button>
  </form></div>
</div></div>

<?php
$vhBase = $u('admin/fees/voteheads/');
$extraScripts = '<script>
function openEditVH(vh){
  document.getElementById("editVHForm").action="'.$vhBase.'"+vh.id+"/update";
  document.getElementById("evhCode").value=vh.code;
  document.getElementById("evhCat").value=vh.category;
  document.getElementById("evhName").value=vh.name;
  document.getElementById("evhBudget").value=vh.budget_amount;
  document.getElementById("evhDesc").value=vh.description||"";
  openModal("editVH");
}
</script>';
?>

