<?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');
  $nic       = $s['nic'] ?? '';
  $reg       = $s['registration_no'] ?? '-';
  $gender    = strtolower(trim((string)($s['gender'] ?? '')));
  $prefix    = ($gender==='female'||$gender==='f')?'Ms.':(($gender==='male'||$gender==='m')?'Mr.':'Mr./Ms.');
  $pronoun   = ($gender==='female'||$gender==='f')?'She':(($gender==='male'||$gender==='m')?'He':'They');

  $course_name = $c['course_name'] ?: 'the program';
  $title = ($course_name ? $course_name.' ' : '') . 'Following Letter';
  $modules = course_modules($db, $c);

  // ---- body html ----
  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>
    We hereby confirm that <?= h($prefix) ?> <strong><?= h($full_name) ?></strong>
    <?php if ($nic!==''): ?>(NIC No. <?= h($nic) ?>),<?php endif; ?>
    is presently a student of our institute, registered under the number
    <strong><?= h($reg) ?></strong>. <?= h($pronoun) ?> is currently following the
    <strong><?= h($course_name) ?></strong> at our institute. The course structure is shown below.
  </p>

  <div class="kv"><strong>Course Structure (Modules)</strong></div>
  <ul>
    <?php foreach ($modules as $m): ?>
      <li><?= h($m) ?></li>
    <?php endforeach; ?>
  </ul>

  <p>
    <?= h($pronoun) ?> has been a dedicated student and is actively participating in the program.
    This letter is issued to confirm <?= strtolower($pronoun)==='they' ? 'their' : (strtolower($pronoun)==='she' ? 'her' : 'his') ?> enrollment and ongoing studies.
  </p>

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