<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Report Card — <?= htmlspecialchars($student['name']) ?></title>
<style>
  *{box-sizing:border-box;margin:0;padding:0}
  body{font-family:'Segoe UI',Arial,sans-serif;font-size:11px;color:#1e293b;background:#f1f5f9;padding:12px}
  .page{background:#fff;max-width:800px;margin:0 auto;border-radius:10px;overflow:hidden;box-shadow:0 4px 24px rgba(0,0,0,.12)}
  /* Header */
  .rc-header{background:linear-gradient(135deg,#1a7f5a,#145f44);color:#fff;padding:12px 20px;display:flex;align-items:center;gap:14px}
  .rc-logo{width:56px;height:56px;border-radius:50%;border:2px solid rgba(255,255,255,.5);overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,.15);font-size:22px;font-weight:800}
  .rc-school{flex:1;text-align:center}
  .rc-school h1{font-size:15px;font-weight:800;letter-spacing:.3px;text-transform:uppercase;margin-bottom:2px}
  .rc-school .rc-sub{font-size:10px;opacity:.85;line-height:1.5}
  .rc-badge{background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.3);border-radius:6px;padding:5px 14px;text-align:center;flex-shrink:0}
  .rc-badge h2{font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.5px}
  .rc-badge p{font-size:9px;opacity:.75;margin-top:2px}
  /* Learner info */
  .rc-info{display:grid;grid-template-columns:repeat(4,1fr);gap:0;border-bottom:1px solid #e2e8f0}
  .rc-info-item{padding:8px 14px;border-right:1px solid #e2e8f0}
  .rc-info-item:last-child{border-right:none}
  .rc-info-label{font-size:9px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:#64748b;margin-bottom:2px}
  .rc-info-value{font-size:12px;font-weight:600;color:#1e293b}
  /* Marks table */
  .rc-section{padding:10px 16px}
  .rc-section h3{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#1a7f5a;margin-bottom:8px;display:flex;align-items:center;gap:8px}
  .rc-section h3::after{content:'';flex:1;height:1px;background:#e2e8f0}
  table{width:100%;border-collapse:collapse;font-size:11px}
  thead tr{background:#1a7f5a;color:#fff}
  th{padding:6px 10px;text-align:left;font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.3px}
  td{padding:6px 10px;border-bottom:1px solid #f1f5f9}
  tr:nth-child(even) td{background:#f8fafc}
  .grade-pill{display:inline-flex;align-items:center;padding:2px 8px;border-radius:20px;font-size:10px;font-weight:700}
  .grade-EE{background:#d1fae5;color:#065f46}
  .grade-ME{background:#dbeafe;color:#1e40af}
  .grade-AE{background:#fef3c7;color:#92400e}
  .grade-BE{background:#fee2e2;color:#991b1b}
  /* Summary */
  .rc-summary{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;padding:10px 16px;background:#f8fafc;border-top:1px solid #e2e8f0;border-bottom:1px solid #e2e8f0}
  .summary-box{background:#fff;border-radius:8px;padding:10px;text-align:center;border:1px solid #e2e8f0}
  .summary-box .val{font-size:22px;font-weight:800;color:#1a7f5a}
  .summary-box .lbl{font-size:10px;color:#64748b;margin-top:2px}
  .mean-box{background:linear-gradient(135deg,#1a7f5a,#145f44);color:#fff;border-radius:8px;padding:10px;text-align:center}
  .mean-box .val{font-size:28px;font-weight:800}
  .mean-box .lbl{font-size:10px;opacity:.8;margin-top:2px}
  /* Competencies */
  .comp-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:6px}
  .comp-item{display:flex;align-items:center;justify-content:space-between;padding:5px 10px;background:#f8fafc;border-radius:6px;border:1px solid #e2e8f0}
  .comp-name{font-size:11px;font-weight:500}
  /* Remarks */
  .remarks-box{background:#f8fafc;border-radius:6px;padding:8px 10px;border:1px solid #e2e8f0;min-height:36px;font-size:11px}
  /* Footer */
  .rc-footer{padding:10px 16px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;border-top:1px solid #e2e8f0}
  .sig-line{border-top:1px solid #94a3b8;padding-top:4px;font-size:10px;color:#64748b;text-align:center;margin-top:20px}
  .print-bar{max-width:800px;margin:0 auto 10px;display:flex;gap:10px;justify-content:flex-end}
  @media print{
    body{background:#fff;padding:0}
    .print-bar{display:none}
    .page{box-shadow:none;border-radius:0}
  }
</style>
</head>
<body>

<!-- Print/Download bar (hidden on print) -->
<div class="print-bar">
  <?php
  $baseUrl = htmlspecialchars(\Core\View::url('admin/exams/'.$exam['id'].'/report/'.$student['id']));
  $tpl = $template ?? 'A';
  ?>
  <div style="display:flex;gap:6px;background:#fff;padding:6px 10px;border-radius:8px;border:1px solid #e2e8f0">
    <span style="font-size:12px;color:#64748b;align-self:center">Template:</span>
    <a href="<?= $baseUrl ?>?template=A" style="padding:5px 12px;border-radius:6px;font-size:12px;font-weight:600;text-decoration:none;<?= $tpl==='A'?'background:#1a7f5a;color:#fff':'background:#f1f5f9;color:#64748b' ?>">
      A — With Competencies
    </a>
    <a href="<?= $baseUrl ?>?template=B" style="padding:5px 12px;border-radius:6px;font-size:12px;font-weight:600;text-decoration:none;<?= $tpl==='B'?'background:#1a7f5a;color:#fff':'background:#f1f5f9;color:#64748b' ?>">
      B — With Class Position
    </a>
  </div>
  <button onclick="window.print()" style="background:#1a7f5a;color:#fff;border:none;padding:10px 20px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;display:flex;align-items:center;gap:8px">
    🖨️ Print / Save as PDF
  </button>
  <button onclick="window.close()" style="background:#f1f5f9;color:#1e293b;border:1px solid #e2e8f0;padding:10px 20px;border-radius:8px;cursor:pointer;font-size:13px">
    ✕ Close
  </button>
</div>

<div class="page">
  <!-- Header -->
  <div class="rc-header">
    <div class="rc-logo">
      <?php if(!empty($school['logo'])): ?>
        <img src="<?= \Core\View::url('storage/uploads/logos/'.$school['logo']) ?>" style="width:56px;height:56px;object-fit:contain;border-radius:50%">
      <?php else: ?>
        <?= strtoupper(substr($school['name'] ?? 'E', 0, 1)) ?>
      <?php endif; ?>
    </div>
    <div class="rc-school">
      <h1><?= htmlspecialchars($school['name'] ?? 'EduSmart School') ?></h1>
      <div class="rc-sub">
        <?php if($school['address'] ?? ''): ?><?= htmlspecialchars($school['address']) ?><?php endif; ?>
        <?php if($school['phone'] ?? ''): ?> &nbsp;|&nbsp; Tel: <?= htmlspecialchars($school['phone']) ?><?php endif; ?>
        <?php if($school['email'] ?? ''): ?> &nbsp;|&nbsp; Email: <?= htmlspecialchars($school['email']) ?><?php endif; ?>
      </div>
    </div>
    <div class="rc-badge">
      <h2>Student Report Card</h2>
      <p><?= htmlspecialchars($exam['name']) ?></p>
      <p><?= date('d F Y') ?></p>
    </div>
  </div>

  <!-- Learner Info -->
  <div class="rc-info">
    <div class="rc-info-item">
      <div class="rc-info-label">Learner Name</div>
      <div class="rc-info-value"><?= htmlspecialchars($student['name']) ?></div>
    </div>
    <div class="rc-info-item">
      <div class="rc-info-label">Assessment No</div>
      <div class="rc-info-value"><?= htmlspecialchars($student['assessment_no']) ?></div>
    </div>
    <div class="rc-info-item">
      <div class="rc-info-label">Grade / Stream</div>
      <div class="rc-info-value"><?= htmlspecialchars(($student['class_name'] ?? '').' '.($student['stream_name'] ?? '')) ?></div>
    </div>
    <div class="rc-info-item">
      <?php if(($template??'A') === 'B' && $classPosition): ?>
      <div class="rc-info-label">Class Position</div>
      <div class="rc-info-value" style="color:#1a7f5a;font-size:16px">
        <?= $classPosition ?><sup style="font-size:9px"><?= match($classPosition){1=>'st',2=>'nd',3=>'rd',default=>'th'} ?></sup>
        <span style="font-size:10px;color:#64748b"> / <?= $classTotal ?></span>
      </div>
      <?php else: ?>
      <div class="rc-info-label">Gender</div>
      <div class="rc-info-value"><?= ucfirst($student['gender'] ?? '—') ?></div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Marks Table -->
  <div class="rc-section">
    <h3>Learning Areas Performance</h3>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>Learning Area / Subject</th>
          <th>Score</th>
          <th>Out Of</th>
          <th>%</th>
          <th>CBC Level</th>
          <th>Remarks</th>
        </tr>
      </thead>
      <tbody>
        <?php
        // Sort marks by score desc for Template B to show ranking
        $sortedMarks = $marks;
        if (($template??'A') === 'B') {
            usort($sortedMarks, fn($a,$b) => $b['score'] <=> $a['score']);
        }
        foreach($sortedMarks as $i => $m):
          $pct = $m['out_of'] > 0 ? round(($m['score']/$m['out_of'])*100, 1) : 0;
          $grade = $m['grade'] ?? ($pct>=75?'EE':($pct>=50?'ME':($pct>=25?'AE':'BE')));
          $fullLevel = ['EE'=>'Exceeding Expectations','ME'=>'Meeting Expectations','AE'=>'Approaching Expectations','BE'=>'Below Expectations'];
        ?>
        <tr>
          <td><?= $i+1 ?></td>
          <td><strong><?= htmlspecialchars($m['subject_name']) ?></strong></td>
          <td><strong><?= $m['score'] ?></strong></td>
          <td><?= $m['out_of'] ?></td>
          <td><?= $pct ?>%</td>
          <td><span class="grade-pill grade-<?= $grade ?>"><?= $grade ?></span></td>
          <td style="color:#64748b"><?= htmlspecialchars($fullLevel[$grade] ?? $m['remarks'] ?? '') ?></td>
        </tr>
        <?php endforeach; ?>
        <?php if(empty($marks)): ?>
        <tr><td colspan="7" style="text-align:center;padding:20px;color:#64748b">No marks recorded for this assessment</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- Summary -->
  <?php
  $totalScore = array_sum(array_column($marks, 'score'));
  $totalOut   = array_sum(array_column($marks, 'out_of')) ?: count($marks)*100;
  $avgPct     = count($marks) > 0 ? round($totalScore / $totalOut * 100, 1) : 0;
  $meanGrade  = $avgPct>=75?'EE':($avgPct>=50?'ME':($avgPct>=25?'AE':'BE'));
  $meanFull   = ['EE'=>'Exceeding Expectations','ME'=>'Meeting Expectations','AE'=>'Approaching Expectations','BE'=>'Below Expectations'];
  $eeCount = 0; $meCount = 0; $aeCount = 0; $beCount = 0;
  foreach ($marks as $m) {
      $g = $m['grade'] ?? '';
      if ($g==='EE') $eeCount++;
      elseif ($g==='ME') $meCount++;
      elseif ($g==='AE') $aeCount++;
      elseif ($g==='BE') $beCount++;
  }
  ?>
  <div class="rc-summary">
    <div class="summary-box" style="display:flex;align-items:center;gap:10px;text-align:left;padding:8px 12px">
      <div style="font-size:30px;font-weight:800;color:#1a7f5a"><?= $avgPct ?>%</div>
      <div><div style="font-size:10px;color:#64748b">Average Score</div><div style="font-size:11px;font-weight:600;color:#1a7f5a"><?= $meanFull[$meanGrade] ?></div></div>
    </div>
    <div class="mean-box" style="display:flex;align-items:center;justify-content:center;gap:10px;padding:8px 12px">
      <div style="font-size:36px;font-weight:800"><?= $meanGrade ?></div>
      <div style="font-size:11px;opacity:.85;max-width:90px;line-height:1.3"><?= $meanFull[$meanGrade] ?></div>
    </div>
    <?php if(($template??'A') === 'B' && $classPosition): ?>
    <div class="summary-box" style="padding:8px 12px;text-align:center">
      <div style="font-size:10px;color:#64748b;margin-bottom:4px">Class Position</div>
      <div style="font-size:32px;font-weight:800;color:#1a7f5a;line-height:1">
        <?= $classPosition ?><sup style="font-size:12px"><?= match($classPosition){1=>'st',2=>'nd',3=>'rd',default=>'th'} ?></sup>
      </div>
      <div style="font-size:10px;color:#64748b">out of <?= $classTotal ?> learners</div>
    </div>
    <?php else: ?>
    <div class="summary-box" style="padding:8px 12px">
      <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:4px;text-align:center">
        <div><div style="font-size:16px;font-weight:700;color:#065f46"><?= $eeCount ?></div><div style="font-size:9px;color:#64748b">EE</div></div>
        <div><div style="font-size:16px;font-weight:700;color:#1e40af"><?= $meCount ?></div><div style="font-size:9px;color:#64748b">ME</div></div>
        <div><div style="font-size:16px;font-weight:700;color:#92400e"><?= $aeCount ?></div><div style="font-size:9px;color:#64748b">AE</div></div>
        <div><div style="font-size:16px;font-weight:700;color:#991b1b"><?= $beCount ?></div><div style="font-size:9px;color:#64748b">BE</div></div>
      </div>
      <div style="font-size:9px;color:#64748b;margin-top:4px;text-align:center">Grade Distribution</div>
    </div>
    <?php endif; ?>
  </div>

  <!-- Competencies — Template A only -->
  <?php if(($template??'A') === 'A' && !empty($competencies)): ?>
  <div class="rc-section">
    <h3>Key Competency Ratings</h3>
    <div class="comp-grid">
      <?php foreach($competencies as $c): ?>
      <div class="comp-item">
        <span class="comp-name"><?= htmlspecialchars($c['name']) ?></span>
        <span class="grade-pill grade-<?= $c['rating'] ?>"><?= $c['rating'] ?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- Class Teacher Remarks -->
  <div class="rc-section">
    <h3>Remarks</h3>
    <?php
    // Auto-generate remarks based on performance
    $autoTeacher = match(true) {
        $avgPct >= 75 => "{$student['name']} has demonstrated exceptional performance this term, exceeding expectations in most learning areas. Keep up the excellent work!",
        $avgPct >= 50 => "{$student['name']} has performed well this term, meeting expectations in the majority of learning areas. With continued effort, even greater results are achievable.",
        $avgPct >= 25 => "{$student['name']} is making progress but needs to put in more effort in several learning areas. Regular revision and active participation in class will help improve performance.",
        default       => "{$student['name']} requires significant improvement and additional support. Please ensure regular attendance, timely completion of assignments, and seek help where necessary.",
    };
    $autoPrincipal = match(true) {
        $avgPct >= 75 => "Excellent performance. We are proud of this learner's dedication and hard work. We encourage continued focus and discipline to maintain this standard.",
        $avgPct >= 50 => "Good performance this term. We encourage the learner to remain consistent and strive for higher achievement in the next assessment.",
        $avgPct >= 25 => "Fair performance. The learner is encouraged to work harder, seek guidance from teachers, and make better use of available learning resources.",
        default       => "Below expectations. The school will provide additional support. Parents/guardians are urged to closely monitor the learner's studies and attend the next parent meeting.",
    };
    $classTeacherRemark = !empty($classTeacherRemark) ? $classTeacherRemark : $autoTeacher;
    $principalRemark    = !empty($principalRemark)    ? $principalRemark    : $autoPrincipal;
    $feeInvoice         = $feeInvoice ?? null;
    ?>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
      <div>
        <div style="font-size:9px;font-weight:600;color:#64748b;margin-bottom:4px">CLASS TEACHER'S REMARKS</div>
        <div class="remarks-box"><?= htmlspecialchars($classTeacherRemark) ?></div>
      </div>
      <div>
        <div style="font-size:9px;font-weight:600;color:#64748b;margin-bottom:4px">PRINCIPAL'S REMARKS</div>
        <div class="remarks-box"><?= htmlspecialchars($principalRemark) ?></div>
      </div>
    </div>
  </div>

  <!-- Fee Balance -->
  <?php if($feeInvoice): ?>
  <div class="rc-section" style="background:#fff8f0;border-top:1px solid #fed7aa">
    <h3 style="color:#c2410c">Fee Account Statement</h3>
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:0;border:1px solid #fed7aa;border-radius:6px;overflow:hidden">
      <div style="padding:8px 10px;border-right:1px solid #fed7aa;text-align:center">
        <div style="font-size:9px;font-weight:700;text-transform:uppercase;color:#92400e;margin-bottom:2px">Term Invoice</div>
        <div style="font-size:13px;font-weight:700">KES <?= number_format($feeInvoice['total_amount'],2) ?></div>
      </div>
      <div style="padding:8px 10px;border-right:1px solid #fed7aa;text-align:center">
        <div style="font-size:9px;font-weight:700;text-transform:uppercase;color:#92400e;margin-bottom:2px">Opening Balance</div>
        <div style="font-size:13px;font-weight:700;color:<?= $feeInvoice['opening_balance']>0?'#dc2626':'#16a34a' ?>">KES <?= number_format($feeInvoice['opening_balance'],2) ?></div>
      </div>
      <div style="padding:8px 10px;border-right:1px solid #fed7aa;text-align:center">
        <div style="font-size:9px;font-weight:700;text-transform:uppercase;color:#92400e;margin-bottom:2px">Amount Paid</div>
        <div style="font-size:13px;font-weight:700;color:#16a34a">KES <?= number_format($feeInvoice['amount_paid'],2) ?></div>
      </div>
      <div style="padding:8px 10px;text-align:center;background:<?= $feeInvoice['balance']>0?'#fef2f2':'#f0fdf4' ?>">
        <div style="font-size:9px;font-weight:700;text-transform:uppercase;color:<?= $feeInvoice['balance']>0?'#991b1b':'#166534' ?>;margin-bottom:2px">Balance Due</div>
        <div style="font-size:15px;font-weight:800;color:<?= $feeInvoice['balance']>0?'#dc2626':'#16a34a' ?>">KES <?= number_format($feeInvoice['balance'],2) ?></div>
        <div style="font-size:9px;margin-top:2px">
          <?php if($feeInvoice['balance']<=0): ?><span style="background:#16a34a;color:#fff;padding:1px 6px;border-radius:8px">FULLY PAID</span>
          <?php elseif($feeInvoice['status']==='partial'): ?><span style="background:#d97706;color:#fff;padding:1px 6px;border-radius:8px">PARTIAL</span>
          <?php else: ?><span style="background:#dc2626;color:#fff;padding:1px 6px;border-radius:8px">OUTSTANDING</span><?php endif; ?>
        </div>
      </div>
    </div>
    <?php if($feeInvoice['balance']>0): ?>
    <div style="margin-top:6px;padding:5px 10px;background:#fef2f2;border-radius:4px;font-size:10px;color:#991b1b;border:1px solid #fecaca">
      <strong>Note:</strong> Please clear the outstanding balance of <strong>KES <?= number_format($feeInvoice['balance'],2) ?></strong> to avoid disruption of learning.
    </div>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <!-- Signatures -->
  <div class="rc-footer">
    <div>
      <div class="sig-line">Class Teacher's Signature</div>
    </div>
    <div>
      <div class="sig-line">Principal's Signature & Stamp</div>
    </div>
    <div>
      <div class="sig-line">Parent / Guardian's Signature</div>
    </div>
  </div>

  <!-- Footer -->
  <div style="padding:12px 24px;background:#f8fafc;text-align:center;font-size:11px;color:#94a3b8;border-top:1px solid #e2e8f0">
    <?= htmlspecialchars($school['name'] ?? 'EduSmart') ?> &mdash; CBC/CBE School Management System &mdash; Generated <?= date('d F Y, H:i') ?>
  </div>
</div>
</body>
</html>

