<?php
require_once __DIR__ . '/../../admin/_nav.php';
require_once VIEWS . '/accountant/_nav.php';
$pageTitle  = 'Scholarships & Discounts';
$_role = \Core\Session::get('user')['role'] ?? '';
$sidebarNav = $_role === 'accountant' ? accountantNav() : adminNav();
$u = function($p) { return \Core\View::url($p); };

$totalValue = 0;
foreach($scholarships as $sc) {
    if($sc['type']==='fixed') $totalValue += (float)$sc['value'];
}
$activeCount = count(array_filter($scholarships, fn($s)=>$s['is_active']));
?>
<div class="page-header">
  <div><h1><i class="bi bi-award"></i> Scholarships & Discounts</h1><p>Fee waivers, bursaries and discounts</p></div>
  <div style="display:flex;gap:8px">
    <a href="<?= $u('admin/finance') ?>" class="btn btn-secondary"><i class="bi bi-speedometer2"></i> Dashboard</a>
    <button onclick="openModal('addScholarship')" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Scholarship</button>
  </div>
</div>

<!-- Summary -->
<div class="grid g3" style="margin-bottom:20px">
  <div class="stat-card" style="">
    <div class="stat-icon si-green"><i class="bi bi-award"></i></div>
    <div class="stat-info"><h3><?= count($scholarships) ?></h3><p>Total Scholarships</p></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-blue"><i class="bi bi-check-circle"></i></div>
    <div class="stat-info"><h3><?= $activeCount ?></h3><p>Active</p></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-amber"><i class="bi bi-cash"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($totalValue) ?></h3><p>Total Fixed Waivers</p></div>
  </div>
</div>

<!-- Type filter tabs -->
<div style="display:flex;gap:8px;margin-bottom:16px">
  <a href="?type=" style="padding:6px 14px;border-radius:20px;font-size:13px;font-weight:500;text-decoration:none;border:2px solid var(--primary);color:var(--primary);background:transparent">All</a>
  <a href="?type=percentage" style="padding:6px 14px;border-radius:20px;font-size:13px;font-weight:500;text-decoration:none;border:2px solid #3b82f6;color:#3b82f6;background:transparent">Percentage</a>
  <a href="?type=fixed" style="padding:6px 14px;border-radius:20px;font-size:13px;font-weight:500;text-decoration:none;border:2px solid var(--success);color:var(--success);background:transparent">Fixed Amount</a>
</div>

<div class="card">
  <div class="table-wrap"><table>
    <thead><tr><th>Student</th><th>Scholarship Name</th><th>Type</th><th>Value</th><th>Sponsor</th><th>Term</th><th>Notes</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
      <?php foreach($scholarships as $sc): ?>
      <tr>
        <td>
          <div style="font-weight:500"><?= htmlspecialchars($sc['student_name']) ?></div>
          <div style="font-size:11px;color:var(--gray)"><?= $sc['assessment_no'] ?></div>
        </td>
        <td><strong><?= htmlspecialchars($sc['name']) ?></strong></td>
        <td>
          <span class="badge <?= $sc['type']==='percentage'?'badge-info':'badge-success' ?>">
            <?= $sc['type']==='percentage'?'Percentage':'Fixed Amount' ?>
          </span>
        </td>
        <td style="font-weight:600;color:var(--success);font-size:15px">
          <?= $sc['type']==='percentage'?$sc['value'].'%':'KES '.number_format($sc['value'],2) ?>
        </td>
        <td style="font-size:12px"><?= htmlspecialchars($sc['sponsor']??'—') ?></td>
        <td style="font-size:12px"><?= htmlspecialchars($sc['term_name']??'All Terms') ?></td>
        <td style="font-size:12px;color:var(--gray);max-width:150px"><?= htmlspecialchars($sc['notes']??'—') ?></td>
        <td><span class="badge <?= $sc['is_active']?'badge-success':'badge-gray' ?>"><?= $sc['is_active']?'Active':'Inactive' ?></span></td>
        <td style="white-space:nowrap">
          <button onclick="openEditScholarship(<?= htmlspecialchars(json_encode($sc),ENT_QUOTES) ?>)" class="btn btn-sm btn-secondary" title="Edit"><i class="bi bi-pencil"></i></button>
          <form method="POST" action="<?= $u('admin/fees/scholarships/'.$sc['id'].'/delete') ?>" style="display:inline" onsubmit="return confirm('Remove this scholarship?')">
            <?= \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($scholarships)): ?><tr><td colspan="9" style="text-align:center;padding:40px;color:var(--gray)"><i class="bi bi-award" style="font-size:32px"></i><p style="margin-top:8px">No scholarships added yet</p></td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>

<!-- Add Scholarship Modal -->
<div class="modal" id="addScholarship"><div class="modal-box">
  <div class="card-header"><h5><i class="bi bi-award"></i> Add Scholarship / Discount</h5><button onclick="closeModal('addScholarship')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body"><form method="POST" action="<?= $u('admin/fees/scholarships/store') ?>">
    <?= \Core\View::csrf() ?>
    <div class="form-group"><label>Student *</label>
      <select name="student_id" required>
        <option value="">Select Student</option>
        <?php foreach($students as $s): ?><option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?> (<?= $s['assessment_no'] ?>)</option><?php endforeach; ?>
      </select>
    </div>
    <div class="form-group"><label>Scholarship / Discount Name *</label><input type="text" name="name" required placeholder="e.g. CDF Bursary, Sibling Discount, Staff Child"></div>
    <div class="grid g2">
      <div class="form-group"><label>Type *</label>
        <select name="type" required id="schType" onchange="updateSchValueLabel()">
          <option value="percentage">Percentage (%)</option>
          <option value="fixed">Fixed Amount (KES)</option>
        </select>
      </div>
      <div class="form-group"><label id="schValueLabel">Value (%) *</label><input type="number" name="value" min="0" step="0.01" required placeholder="e.g. 50 or 5000"></div>
      <div class="form-group"><label>Sponsor / Donor</label><input type="text" name="sponsor" placeholder="e.g. CDF, School Board, NGO"></div>
      <div class="form-group"><label>Term (optional)</label>
        <select name="term_id">
          <option value="">All Terms</option>
          <?php foreach($terms as $t): ?><option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['year_name'].' '.$t['name']) ?></option><?php endforeach; ?>
        </select>
      </div>
    </div>
    <div class="form-group"><label>Notes</label><textarea name="notes" rows="2" placeholder="Additional details about this scholarship"></textarea></div>
    <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Add Scholarship</button>
  </form></div>
</div></div>

<!-- Edit Scholarship Modal (view-only info + delete) -->
<div class="modal" id="editScholarship"><div class="modal-box">
  <div class="card-header"><h5>Scholarship Details</h5><button onclick="closeModal('editScholarship')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <div id="editSchDetails" style="font-size:13px;line-height:1.8"></div>
    <div style="margin-top:16px;padding:12px;background:var(--light);border-radius:8px;font-size:12px;color:var(--gray)">
      <i class="bi bi-info-circle"></i> To modify, delete and re-add with correct details.
    </div>
    <div style="margin-top:14px"><button onclick="closeModal('editScholarship')" class="btn btn-secondary">Close</button></div>
  </div>
</div></div>

<?php $extraScripts = '<script>
function updateSchValueLabel(){
  var t=document.getElementById("schType").value;
  document.getElementById("schValueLabel").textContent=t==="percentage"?"Value (%) *":"Amount (KES) *";
}
function openEditScholarship(sc){
  var val=sc.type==="percentage"?sc.value+"%":"KES "+parseFloat(sc.value).toLocaleString("en-KE",{minimumFractionDigits:2});
  document.getElementById("editSchDetails").innerHTML=
    "<strong>"+sc.name+"</strong><br>"+
    "Student: "+sc.student_name+" ("+sc.assessment_no+")<br>"+
    "Type: "+(sc.type==="percentage"?"Percentage":"Fixed Amount")+" | Value: "+val+"<br>"+
    "Sponsor: "+(sc.sponsor||"—")+" | Term: "+(sc.term_name||"All Terms")+"<br>"+
    "Status: "+(sc.is_active?"Active":"Inactive")+"<br>"+
    "Notes: "+(sc.notes||"—");
  openModal("editScholarship");
}
</script>'; ?>


