<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$shared = __DIR__ . '/../../includes/letters_shared.php';
if (!is_file($shared)) {
  $shared = __DIR__ . '/letters_shared.php';
}
require_once $shared;


try {
  $student_id = (int)($_GET['student_id'] ?? 0);
  $batch_id   = isset($_GET['batch_id']) ? (int)$_GET['batch_id'] : null;
  if ($student_id <= 0) throw new Exception('Missing student_id');

  $ctx = fetch_context($db, $student_id, $batch_id);
  $s = $ctx['student']; $c = $ctx['course']; $b = $ctx['batch'];

  $full_name = $s['full_name'] ?? ($s['name'] ?? 'Student');
  $reg       = $s['registration_no'] ?? '-';
  $nic       = $s['nic'] ?? '';
  $course_name = $c['course_name'] ?: '—';

  // Aggregate results if available
  $rows = fetch_results($db, $s, $c);
  $sumScore = 0.0;
$sumTotal = 0.0;

foreach ($rows as $r) {
  $score = (float)($r['score'] ?? 0);
  $total = (float)($r['total'] ?? 0);

  if ($total > 0) {
    $normalizedScore = ($score / $total) * 100;
    $sumScore += $normalizedScore;
    $sumTotal += 100;
  }
}

$pct = $sumTotal > 0 ? round(($sumScore / $sumTotal) * 100, 2) : null;
  $grade = pct_to_grade($pct);

  $title = 'Completion & Results Summary';

  ob_start();
  $ins = inst();
  ?>
  <div class="hdr">
    <div>
      <div class="name"><?= h($ins['name']) ?></div>
      <div class="muted"><?= h($ins['address']) ?> · <?= h($ins['phone']) ?> · <?= h($ins['email']) ?></div>
    </div>
    <div class="muted"><?= h(ordinal_date()) ?></div>
  </div>

  <div class="title"><?= h($title) ?></div>

  <p>To Whom It May Concern,</p>
  <p>
    This is to certify that <strong><?= h($full_name) ?></strong>
    (Reg/Ref: <strong><?= h($reg) ?></strong><?php if($nic){ ?>, NIC No. <?= h($nic) ?><?php } ?>)
    has successfully completed the <strong><?= h($course_name) ?></strong> at our institute.
  </p>

  <table>
    <tr><th style="width:40%">Student Name</th><td><?= h($full_name) ?></td></tr>
    <tr><th>Reg/Ref No</th><td><?= h($reg) ?></td></tr>
    <tr><th>Course</th><td><?= h($course_name) ?></td></tr>
    <tr><th>Batch</th><td><?= h($b['batch_name'] ?? '—') ?></td></tr>
    <tr><th>Total Score</th><td><?= $sumTotal>0 ? number_format($sumScore,2).' / '.number_format($sumTotal,2) : '—' ?></td></tr>
    <tr><th>Overall %</th><td><?= $pct!==null ? number_format($pct,2).'%' : '—' ?></td></tr>
    <tr><th>Overall Grade</th><td><?= h($grade) ?></td></tr>
  </table>

  <?php if ($rows): ?>
    <div class="kv" style="margin-top:8mm"><strong>Module-wise Results</strong></div>
    <table>
      <thead>
        <tr>
          <th style="width:40%">Module</th>
          <th>Score</th>
          <th>Total</th>
          <th>Grade</th>
          <th>Date</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
  <?php
    $rawScore = (float)($r['score'] ?? 0);
    $rawTotal = (float)($r['total'] ?? 0);
    $displayScore = $rawTotal > 0 ? round(($rawScore / $rawTotal) * 100, 2) : 0;
  ?>
  <tr>
    <td><?= h($r['module_name'] ?? '') ?></td>
    <td><?= h(number_format($displayScore, 2)) ?></td>
    <td>100.00</td>
    <td><?= h($r['grade'] ?? '') ?></td>
    <td><?= h($r['date_taken'] ?? '') ?></td>
  </tr>
<?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>

  <div class="sig-row">
    <div class="sig">
      <div>___________________________</div>
      <div><strong>Branch Manager</strong><br>EDEN Campus</div>
    </div>
    <div class="sig"></div>
  </div>
  <?php
  $body = ob_get_clean();

  render_letter_page($title, $body, $title.' - '.$full_name);
} catch (Throwable $e) {
  http_response_code(400);
  echo "Error: " . h($e->getMessage());
}
