<?php
require_once __DIR__ . '/../../admin/_nav.php';
$pageTitle  = 'Results — '.$exam['name'];
$sidebarNav = adminNav();
$u = function($p) { return \Core\View::url($p); };
$levelFull  = ['EE'=>'Exceeding','ME'=>'Meeting','AE'=>'Approaching','BE'=>'Below'];
$levelColor = ['EE'=>'badge-success','ME'=>'badge-info','AE'=>'badge-warning','BE'=>'badge-danger'];
?>

<div class="page-header">
  <div>
    <h1><i class="bi bi-bar-chart-line"></i> <?= htmlspecialchars($exam['name']) ?></h1>
    <p>
      <span class="badge badge-info"><?= strtoupper($exam['type']) ?></span>
      &bull; <?= $exam['is_published'] ? '<span class="badge badge-success">Published</span>' : '<span class="badge badge-warning">Draft</span>' ?>
    </p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <?php if(!$exam['is_published']): ?>
    <form method="POST" action="<?= $u('admin/exams/'.$exam['id'].'/publish') ?>" style="display:inline">
      <?= \Core\View::csrf() ?>
      <button class="btn btn-primary" onclick="return confirm('Publish results? Parents will be able to view them.')">
        <i class="bi bi-send"></i> Publish Results
      </button>
    </form>
    <?php endif; ?>
    <a href="<?= $u('admin/exams') ?>" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Back</a>
  </div>
</div>

<!-- Stream selector -->
<div class="card" style="margin-bottom:16px">
  <div class="card-body" style="padding:14px">
    <form method="GET" style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end">
      <div class="form-group" style="margin:0;flex:1;min-width:200px">
        <label style="font-size:12px">Select Grade / Stream</label>
        <select name="stream_id" onchange="this.form.submit()">
          <option value="">-- Select Stream --</option>
          <?php foreach($streams as $s): ?>
          <option value="<?= $s['id'] ?>" <?= $streamId==$s['id']?'selected':'' ?>><?= htmlspecialchars($s['full_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </form>
  </div>
</div>

<?php if(!empty($results)): ?>

<!-- Action bar -->
<div class="card" style="margin-bottom:16px">
  <div class="card-body" style="padding:12px 16px;display:flex;gap:10px;flex-wrap:wrap;align-items:center">
    <strong style="font-size:13px"><i class="bi bi-people"></i> <?= count($results) ?> Learners</strong>
    <div style="flex:1"></div>

    <!-- Print all report cards -->
    <button onclick="printAllReportCards()" class="btn btn-secondary">
      <i class="bi bi-printer"></i> Print All Report Cards
    </button>

    <!-- Send results to parents -->
    <form method="POST" action="<?= $u('admin/exams/'.$exam['id'].'/send-results') ?>" style="display:inline">
      <?= \Core\View::csrf() ?>
      <input type="hidden" name="stream_id" value="<?= $streamId ?>">
      <button class="btn btn-primary" onclick="return confirm('Send results notification to all parents of this stream?')">
        <i class="bi bi-bell"></i> Notify Parents
      </button>
    </form>
  </div>
</div>

<!-- Summary stats -->
<?php
$allGrades = array_column($results, 'mean_grade');
$dist = array_count_values($allGrades);
$total = count($results);
?>
<div class="grid g4" style="margin-bottom:16px">
  <?php foreach(['EE'=>['#065f46','#d1fae5','Exceeding'],'ME'=>['#1e40af','#dbeafe','Meeting'],'AE'=>['#92400e','#fef3c7','Approaching'],'BE'=>['#991b1b','#fee2e2','Below']] as $g=>[$tc,$bg,$lbl]): ?>
  <div class="stat-card">
    <div class="stat-icon" style="background:<?= $bg ?>;color:<?= $tc ?>"><strong style="font-size:16px"><?= $g ?></strong></div>
    <div class="stat-info">
      <h3><?= $dist[$g] ?? 0 ?></h3>
      <p><?= $lbl ?> (<?= $total>0?round((($dist[$g]??0)/$total)*100,1):0 ?>%)</p>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Results table -->
<div class="card" id="resultsTable">
  <div class="card-header">
    <h5><i class="bi bi-table"></i> Stream Results</h5>
    <button onclick="window.print()" class="btn btn-sm btn-secondary"><i class="bi bi-printer"></i> Print Table</button>
  </div>
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>Pos</th>
          <th>Adm No</th>
          <th>Learner Name</th>
          <?php foreach($subjects as $sub): ?>
          <th style="min-width:80px" title="<?= htmlspecialchars($sub['name']) ?>"><?= htmlspecialchars($sub['code'] ?: substr($sub['name'],0,5)) ?></th>
          <?php endforeach; ?>
          <th>Avg %</th>
          <th>Level</th>
          <th style="min-width:130px">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($results as $r):
          $scores = array_column($r['marks'], 'score');
          $avgPct = count($scores)>0 ? round(array_sum($scores)/count($scores),1) : 0;
        ?>
        <tr>
          <td>
            <div style="width:28px;height:28px;border-radius:50%;background:<?= $r['position']<=3?'#1a7f5a':'var(--light)' ?>;color:<?= $r['position']<=3?'#fff':'var(--dark)' ?>;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:12px">
              <?= $r['position'] ?>
            </div>
          </td>
          <td style="font-size:12px;color:var(--gray)"><?= htmlspecialchars($r['assessment_no']) ?></td>
          <td>
            <div style="display:flex;align-items:center;gap:8px">
              <div class="avatar" style="width:28px;height:28px;font-size:11px;flex-shrink:0"><?= strtoupper(substr($r['student_name'],0,1)) ?></div>
              <span style="font-weight:500"><?= htmlspecialchars($r['student_name']) ?></span>
            </div>
          </td>
          <?php foreach($subjects as $sub):
            $mk = $r['marks'][$sub['id']] ?? null;
            $g  = $mk['grade'] ?? '—';
            $cls = $levelColor[$g] ?? 'badge-gray';
          ?>
          <td style="text-align:center">
            <?php if($mk): ?>
            <div style="font-weight:600;font-size:13px"><?= $mk['score'] ?></div>
            <span class="badge <?= $cls ?>" style="font-size:10px;padding:1px 6px"><?= $g ?></span>
            <?php else: ?>
            <span style="color:var(--gray)">—</span>
            <?php endif; ?>
          </td>
          <?php endforeach; ?>
          <td><strong><?= $avgPct ?>%</strong></td>
          <td>
            <span class="badge <?= $levelColor[$r['mean_grade']] ?? 'badge-gray' ?>">
              <?= $r['mean_grade'] ?> — <?= $levelFull[$r['mean_grade']] ?? '' ?>
            </span>
          </td>
          <td>
            <div style="display:flex;gap:4px">
              <a href="<?= $u('admin/exams/'.$exam['id'].'/report/'.$r['student_id']) ?>"
                 target="_blank" class="btn btn-sm btn-primary" title="View Report Card">
                <i class="bi bi-file-person"></i> Report
              </a>
              <button onclick="printOne(<?= $exam['id'] ?>,<?= $r['student_id'] ?>)"
                      class="btn btn-sm btn-secondary" title="Print Report Card">
                <i class="bi bi-printer"></i>
              </button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php else: ?>
<?php if($streamId): ?>
<div class="card"><div class="card-body" style="text-align:center;padding:50px;color:var(--gray)">
  <i class="bi bi-inbox" style="font-size:40px;display:block;margin-bottom:12px"></i>
  No marks entered for this stream yet.
  <br><a href="<?= $u('admin/exams/'.$exam['id'].'/marks?stream_id='.$streamId) ?>" class="btn btn-primary" style="margin-top:16px"><i class="bi bi-pencil-square"></i> Enter Marks</a>
</div></div>
<?php else: ?>
<div class="card"><div class="card-body" style="text-align:center;padding:50px;color:var(--gray)">
  <i class="bi bi-arrow-up-circle" style="font-size:40px;display:block;margin-bottom:12px"></i>
  Select a stream above to view results.
</div></div>
<?php endif; ?>
<?php endif; ?>

<?php $extraScripts = '
<script>
function printOne(examId, studentId) {
  const url = "' . \Core\View::url('admin/exams/') . '" + examId + "/report/" + studentId;
  const w = window.open(url, "_blank", "width=900,height=700");
  w.onload = () => w.print();
}

function printAllReportCards() {
  const rows = document.querySelectorAll("tbody tr");
  const ids  = [];
  rows.forEach(row => {
    const btn = row.querySelector("a[href*=\'/report/\']");
    if (btn) ids.push(btn.href);
  });
  if (!ids.length) { alert("No results to print."); return; }
  if (!confirm("Open " + ids.length + " report cards for printing?")) return;
  ids.forEach((url, i) => setTimeout(() => window.open(url, "_blank"), i * 400));
}
</script>'; ?>

