<?php
$pageTitle  = $student['name'];
$sidebarNav = '<div class="nav-section">Parent Portal</div>
<div class="nav-item"><a href="'.\Core\View::url('parent/dashboard').'"><i class="bi bi-grid"></i> Dashboard</a></div>
<div class="nav-item"><a href="'.\Core\View::url('profile').'"><i class="bi bi-person-circle"></i> Profile</a></div>';
$u   = function($p) { return \Core\View::url($p); };
$bal = (float)($currentInvoice['total_amount'] ?? 0) - (float)($currentInvoice['amount_paid'] ?? 0);

// Group marks by exam
$marksByExam = [];
foreach ($recentMarks as $m) {
    $marksByExam[$m['exam_id']]['exam_name'] = $m['exam_name'];
    $marksByExam[$m['exam_id']]['term_name'] = $m['term_name'];
    $marksByExam[$m['exam_id']]['subjects'][] = $m;
}
?>
<div class="page-header">
  <div style="display:flex;align-items:center;gap:16px">
    <div class="avatar" style="width:52px;height:52px;font-size:20px"><?= strtoupper(substr($student['name'],0,1)) ?></div>
    <div>
      <h1><?= htmlspecialchars($student['name']) ?></h1>
      <p><?= htmlspecialchars(($student['class_name']??'').' '.($student['stream_name']??'')) ?> &bull; <?= htmlspecialchars($student['assessment_no']) ?></p>
    </div>
  </div>
  <a href="<?= $u('parent/dashboard') ?>" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Back</a>
</div>

<!-- KPI -->
<div class="grid g3" style="margin-bottom:24px">
  <div class="stat-card">
    <div class="stat-icon si-green"><i class="bi bi-check-circle"></i></div>
    <div class="stat-info"><h3><?= $summary['present'] ?? 0 ?></h3><p>Days Present</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-red"><i class="bi bi-x-circle"></i></div>
    <div class="stat-info"><h3><?= $summary['absent'] ?? 0 ?></h3><p>Days Absent</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon <?= $bal>0?'si-red':'si-green' ?>"><i class="bi bi-cash"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($bal) ?></h3><p>Fee Balance</p></div>
  </div>
</div>

<div class="grid g2" style="align-items:start">

  <!-- Results by Exam -->
  <div>
    <div class="card">
      <div class="card-header">
        <h5><i class="bi bi-journal-text"></i> Results</h5>
        <span style="font-size:12px;color:var(--gray)"><?= count($exams) ?> published assessments</span>
      </div>
      <?php if(empty($exams)): ?>
      <div class="card-body" style="text-align:center;color:var(--gray);padding:40px">
        <i class="bi bi-journal-x" style="font-size:32px;display:block;margin-bottom:8px"></i>
        No published results yet
      </div>
      <?php else: ?>
      <?php foreach($exams as $exam): ?>
      <div style="padding:14px 18px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:12px">
        <div>
          <div style="font-weight:600;font-size:14px"><?= htmlspecialchars($exam['name']) ?></div>
          <div style="font-size:12px;color:var(--gray)"><?= htmlspecialchars($exam['year_name'].' — '.$exam['term_name']) ?></div>
          <?php if(isset($marksByExam[$exam['id']])): ?>
          <div style="font-size:12px;color:var(--gray);margin-top:2px">
            <?= count($marksByExam[$exam['id']]['subjects']) ?> subjects &bull;
            Avg: <?= round(array_sum(array_column($marksByExam[$exam['id']]['subjects'],'score')) / count($marksByExam[$exam['id']]['subjects']), 1) ?>%
          </div>
          <?php endif; ?>
        </div>
        <a href="<?= $u('parent/student/'.$student['id'].'/results/'.$exam['id']) ?>"
           target="_blank"
           class="btn btn-sm btn-primary"
           style="white-space:nowrap">
          <i class="bi bi-download"></i> Download
        </a>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>

  <!-- Fees + Attendance -->
  <div style="display:flex;flex-direction:column;gap:16px">
    <div class="card">
      <div class="card-header"><h5><i class="bi bi-receipt"></i> Current Term Fees</h5>
        <a href="<?= $u('parent/fees/history/'.$student['id']) ?>" class="btn btn-sm btn-secondary"><i class="bi bi-clock-history"></i> History</a>
      </div>
      <div class="card-body">
        <?php if($currentInvoice): ?>
        <!-- Paybill Info -->
        <?php $school = \Core\Session::get('school') ?? []; ?>
        <div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:8px;padding:12px 14px;margin-bottom:12px">
          <div style="font-size:11px;font-weight:700;color:#1e40af;text-transform:uppercase;margin-bottom:6px"><i class="bi bi-phone"></i> Pay via M-Pesa Paybill</div>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;font-size:13px">
            <div><div style="font-size:10px;color:#64748b">Paybill Number</div><div style="font-weight:800;font-size:16px;color:#1e40af"><?= htmlspecialchars($mpesaPaybill ?: 'See school notice') ?></div></div>
            <div><div style="font-size:10px;color:#64748b">Account Number</div><div style="font-weight:800;font-size:16px;color:#1e40af"><?= htmlspecialchars($student['assessment_no']) ?></div></div>
          </div>
          <div style="font-size:10px;color:#3b82f6;margin-top:6px"><i class="bi bi-info-circle"></i> Use your child's assessment number as the account number when paying via Paybill</div>
        </div>
        <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border)">
          <span style="color:var(--gray)">Total Fee</span><strong>KES <?= number_format($currentInvoice['total_amount']) ?></strong>
        </div>
        <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border)">
          <span style="color:var(--gray)">Paid</span><strong style="color:var(--success)">KES <?= number_format($currentInvoice['amount_paid']) ?></strong>
        </div>
        <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border)">
          <span style="color:var(--gray)">Balance</span>
          <strong style="color:<?= $bal>0?'var(--danger)':'var(--success)' ?>">KES <?= number_format($bal) ?></strong>
        </div>
        <span class="badge <?= $currentInvoice['status']==='paid'?'badge-success':($currentInvoice['status']==='partial'?'badge-warning':'badge-danger') ?>" style="margin-top:8px">
          <?= ucfirst($currentInvoice['status']) ?>
        </span>

        <?php if($bal > 0): ?>
        <!-- STK Push Payment -->
        <div style="margin-top:16px;padding:14px;background:linear-gradient(135deg,#f0fdf4,#dcfce7);border-radius:10px;border:1px solid #86efac">
          <div style="font-weight:700;font-size:13px;color:#166534;margin-bottom:10px"><i class="bi bi-phone"></i> Pay via M-Pesa STK Push</div>
          <form method="POST" action="<?= $u('parent/student/'.$student['id'].'/pay') ?>" id="stkForm">
            <?= \Core\View::csrf() ?>
            <input type="hidden" name="invoice_id" value="<?= $currentInvoice['id'] ?>">
            <div style="display:flex;gap:8px;flex-wrap:wrap">
              <div style="flex:1;min-width:140px">
                <label style="font-size:11px;font-weight:600;color:#166534">Phone Number</label>
                <input type="tel" name="phone" placeholder="0712345678" required
                  style="width:100%;padding:8px 10px;border:1px solid #86efac;border-radius:6px;font-size:13px;margin-top:3px">
              </div>
              <div style="flex:1;min-width:120px">
                <label style="font-size:11px;font-weight:600;color:#166534">Amount (KES)</label>
                <input type="number" name="amount" value="<?= $bal ?>" min="1" max="<?= $bal ?>" required
                  style="width:100%;padding:8px 10px;border:1px solid #86efac;border-radius:6px;font-size:13px;margin-top:3px">
              </div>
            </div>
            <button type="submit" id="stkBtn"
              style="width:100%;margin-top:10px;background:#16a34a;color:#fff;border:none;padding:10px;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px">
              <i class="bi bi-phone-vibrate"></i> Send STK Push
            </button>
          </form>
          <div style="font-size:10px;color:#166534;margin-top:6px;text-align:center">You will receive a prompt on your phone to enter your M-Pesa PIN</div>
          <?php if(\Core\Session::get('stk_invoice_id') == $currentInvoice['id']): ?>
          <div id="stkStatus" style="margin-top:10px;padding:8px;background:#fff;border-radius:6px;border:1px solid #86efac;font-size:12px;text-align:center;color:#166534">
            <i class="bi bi-hourglass-split"></i> Waiting for payment confirmation...
          </div>
          <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php else: ?>
        <div style="text-align:center;color:var(--gray)">No invoice for current term</div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Quick marks preview -->
    <?php if(!empty($marksByExam)): ?>
    <?php $latestExamId = array_key_first($marksByExam); $latest = $marksByExam[$latestExamId]; ?>
    <div class="card">
      <div class="card-header">
        <h5><i class="bi bi-bar-chart"></i> Latest: <?= htmlspecialchars($latest['exam_name']) ?></h5>
        <span style="font-size:12px;color:var(--gray)"><?= htmlspecialchars($latest['term_name']) ?></span>
      </div>
      <div class="card-body" style="padding:0">
        <?php foreach($latest['subjects'] as $m): ?>
        <div style="padding:10px 18px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center">
          <span style="font-size:13px"><?= htmlspecialchars($m['subject_name']) ?></span>
          <div style="display:flex;align-items:center;gap:8px">
            <strong><?= $m['score'] ?>%</strong>
            <span class="badge badge-info"><?= htmlspecialchars($m['grade']) ?></span>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>

</div>
