<?php
require_once __DIR__ . '/../../admin/_nav.php';
require_once VIEWS . '/accountant/_nav.php';
$pageTitle  = 'Fee Structure';
$_role = \Core\Session::get('user')['role'] ?? '';
$sidebarNav = $_role === 'accountant' ? accountantNav() : adminNav();
$u = function($p) { return \Core\View::url($p); };
$categories = ['tuition'=>'Tuition','transport'=>'Transport','boarding'=>'Boarding','meals'=>'Meals','activity'=>'Activity','other'=>'Other'];
$catColors  = ['tuition'=>'#3b82f6','transport'=>'#f59e0b','boarding'=>'#8b5cf6','meals'=>'#10b981','activity'=>'#ef4444','other'=>'#6b7280'];
?>
<div class="page-header">
  <div><h1><i class="bi bi-list-ul"></i> Fee Structure</h1><p>Define fee components per term/class</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="POST" action="<?= $u('admin/fees/generate') ?>" style="display:flex;gap:8px">
      <?= \Core\View::csrf() ?>
      <select name="term_id" required style="width:180px">
        <option value="">Select Term</option>
        <?php foreach($terms as $t): ?><option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['year_name'].' '.$t['name']) ?></option><?php endforeach; ?>
      </select>
      <button type="submit" class="btn btn-secondary"><i class="bi bi-lightning"></i> Generate Invoices</button>
    </form>
    <button onclick="openModal('addFee')" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Fee Item</button>
  </div>
</div>

<!-- Summary by category -->
<?php
$byCat = [];
foreach ($structures as $f) $byCat[$f['category'] ?? 'other'][] = $f;
?>
<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:20px">
  <?php foreach($categories as $key => $label): if(empty($byCat[$key])) continue; ?>
  <div style="background:#fff;border:2px solid <?= $catColors[$key] ?>33;border-radius:10px;padding:12px 18px;min-width:140px">
    <div style="font-size:11px;color:<?= $catColors[$key] ?>;font-weight:700;text-transform:uppercase"><?= $label ?></div>
    <div style="font-size:18px;font-weight:700;margin-top:4px"><?= count($byCat[$key]) ?> items</div>
    <div style="font-size:12px;color:var(--gray)">KES <?= number_format(array_sum(array_column($byCat[$key],'amount'))) ?></div>
  </div>
  <?php endforeach; ?>
</div>

<div class="card">
  <div class="table-wrap"><table>
    <thead><tr><th>Name</th><th>Category</th><th>Term</th><th>Class</th><th>Amount</th><th>Mandatory</th><th>Actions</th></tr></thead>
    <tbody>
      <?php foreach($structures as $f): $col = $catColors[$f['category'] ?? 'other'] ?? '#6b7280'; ?>
      <tr>
        <td>
          <strong><?= htmlspecialchars($f['name']) ?></strong>
          <?php if($f['description'] ?? ''): ?><div style="font-size:11px;color:var(--gray)"><?= htmlspecialchars($f['description']) ?></div><?php endif; ?>
        </td>
        <td><span class="badge" style="background:<?= $col ?>22;color:<?= $col ?>"><?= $categories[$f['category'] ?? 'other'] ?? ucfirst($f['category']) ?></span></td>
        <td style="font-size:12px"><?= htmlspecialchars($f['term_name']) ?></td>
        <td style="font-size:12px"><?= htmlspecialchars($f['class_name'] ?? 'All Classes') ?></td>
        <td><strong>KES <?= number_format($f['amount'],2) ?></strong></td>
        <td><span class="badge <?= $f['is_mandatory']?'badge-success':'badge-gray' ?>"><?= $f['is_mandatory']?'Yes':'No' ?></span></td>
        <td style="white-space:nowrap">
          <button onclick="openEditFee(<?= htmlspecialchars(json_encode($f), ENT_QUOTES) ?>)" class="btn btn-sm btn-secondary"><i class="bi bi-pencil"></i></button>
          <form method="POST" action="<?= $u('admin/fees/structure/'.$f['id'].'/delete') ?>" style="display:inline" onsubmit="return confirm('Delete this fee item?')">
            <?= \Core\View::csrf() ?>
            <button type="submit" class="btn btn-sm btn-danger"><i class="bi bi-trash"></i></button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if(empty($structures)): ?><tr><td colspan="7" style="text-align:center;padding:40px;color:var(--gray)">No fee items yet. Add your first fee component.</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>

<!-- Add Fee Modal -->
<div class="modal" id="addFee"><div class="modal-box">
  <div class="card-header"><h5>Add Fee Item</h5><button onclick="closeModal('addFee')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body"><form method="POST" action="<?= $u('admin/fees/structure/store') ?>">
    <?= \Core\View::csrf() ?>
    <div class="grid g2">
      <div class="form-group"><label>Fee Name *</label><input type="text" name="name" placeholder="e.g. Tuition Fee" required></div>
      <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>Amount (KES) *</label><input type="number" name="amount" min="0" step="0.01" required></div>
      <div class="form-group"><label>Term *</label>
        <select name="term_id" required>
          <option value="">Select Term</option>
          <?php foreach($terms as $t): ?><option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['year_name'].' '.$t['name']) ?></option><?php endforeach; ?>
        </select>
      </div>
      <div class="form-group"><label>Class (optional)</label>
        <select name="class_id">
          <option value="">All Classes</option>
          <?php foreach($classes as $c): ?><option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option><?php endforeach; ?>
        </select>
      </div>
      <div class="form-group"><label>Mandatory?</label>
        <select name="is_mandatory"><option value="1">Yes</option><option value="0">No</option></select>
      </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">Add Fee Item</button>
  </form></div>
</div></div>

<!-- Edit Fee Modal -->
<div class="modal" id="editFee"><div class="modal-box">
  <div class="card-header"><h5>Edit Fee Item</h5><button onclick="closeModal('editFee')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body"><form method="POST" id="editFeeForm" action="">
    <?= \Core\View::csrf() ?>
    <div class="grid g2">
      <div class="form-group"><label>Fee Name *</label><input type="text" name="name" id="editFeeName" required></div>
      <div class="form-group"><label>Category *</label>
        <select name="category" id="editFeeCategory">
          <?php foreach($categories as $k=>$v): ?><option value="<?= $k ?>"><?= $v ?></option><?php endforeach; ?>
        </select>
      </div>
      <div class="form-group"><label>Amount (KES) *</label><input type="number" name="amount" id="editFeeAmount" min="0" step="0.01" required></div>
      <div class="form-group"><label>Class</label>
        <select name="class_id" id="editFeeClass">
          <option value="">All Classes</option>
          <?php foreach($classes as $c): ?><option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option><?php endforeach; ?>
        </select>
      </div>
      <div class="form-group"><label>Mandatory?</label>
        <select name="is_mandatory" id="editFeeMandatory"><option value="1">Yes</option><option value="0">No</option></select>
      </div>
    </div>
    <div class="form-group"><label>Description</label><input type="text" name="description" id="editFeeDesc"></div>
    <button type="submit" class="btn btn-primary">Update Fee Item</button>
  </form></div>
</div></div>

<?php
$feeBaseUrl = $u('admin/fees/structure/');
$extraScripts = '<script>
function openEditFee(f){
  document.getElementById("editFeeForm").action="'.$feeBaseUrl.'"+f.id+"/update";
  document.getElementById("editFeeName").value=f.name;
  document.getElementById("editFeeCategory").value=f.category||"tuition";
  document.getElementById("editFeeAmount").value=f.amount;
  document.getElementById("editFeeClass").value=f.class_id||"";
  document.getElementById("editFeeMandatory").value=f.is_mandatory;
  document.getElementById("editFeeDesc").value=f.description||"";
  openModal("editFee");
}
</script>';
?>

