<?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'] ?: '—';

  $title = 'Enrollment Confirmation';

  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 confirms that <strong><?= h($full_name) ?></strong>
    (Reg/Ref: <strong><?= h($reg) ?></strong><?php if($nic){ ?>, NIC No. <?= h($nic) ?><?php } ?>)
    has been enrolled at our institution for the <strong><?= h($course_name) ?></strong>.
  </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>Batch Start</th><td><?= h($b['batch_start_date'] ?? '—') ?></td></tr>
    <tr><th>Batch End</th><td><?= h($b['batch_end_date'] ?? '—') ?></td></tr>
  </table>

  <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());
}