<?php
// student/get_units.php
session_start();
mysqli_report(MYSQLI_REPORT_OFF);
require_once "../includes/db.php"; // may define $mysqli, $conn, or db()

// Pick a DB handle robustly
$db = null;
if (isset($mysqli) && $mysqli instanceof mysqli) { $db = $mysqli; }
elseif (isset($conn) && $conn instanceof mysqli) { $db = $conn; }
elseif (function_exists('db')) { $db = db(); }

if (!$db) { http_response_code(500); echo '<option value="">-- DB error --</option>'; exit; }

$course_name = trim($_GET['course_name'] ?? '');
if ($course_name === '') { echo '<option value="">-- Select Unit --</option>'; exit; }

header("Content-Type: text/html; charset=UTF-8");

// Try to resolve course_id from normalized 'courses' table (if present)
$cid = null;
$hasCourses = $db->query("SHOW TABLES LIKE 'courses'");
if ($hasCourses && $hasCourses->num_rows > 0) {
  if ($st = $db->prepare("SELECT id FROM courses WHERE TRIM(course_name)=TRIM(?) LIMIT 1")) {
    $st->bind_param("s", $course_name);
    if ($st->execute()) {
      $row = $st->get_result()->fetch_assoc();
      if ($row) { $cid = (int)$row['id']; }
    }
    $st->close();
  }
}

// Build units query (prefer course_id, fallback to text match)
if ($cid !== null) {
  $sql = "SELECT DISTINCT name FROM units
          WHERE course_id=? OR TRIM(course_name)=TRIM(?)
          ORDER BY name";
  $st2 = $db->prepare($sql);
  $st2->bind_param("is", $cid, $course_name);
} else {
  $sql = "SELECT DISTINCT name FROM units
          WHERE TRIM(course_name)=TRIM(?)
          ORDER BY name";
  $st2 = $db->prepare($sql);
  $st2->bind_param("s", $course_name);
}

if ($st2 && $st2->execute()) {
  $res = $st2->get_result();
  if ($res && $res->num_rows) {
    while ($u = $res->fetch_assoc()) {
      $name = htmlspecialchars($u['name'] ?? '', ENT_QUOTES, 'UTF-8');
      if ($name !== '') {
        echo '<option value="'.$name.'">'.$name.'</option>';
      }
    }
  } else {
    echo '<option value="">-- No units found --</option>';
  }
  $st2->close();
} else {
  echo '<option value="">-- Query error --</option>';
}
