<?php
require_once "../includes/db.php";

$course_name = trim($_GET['course_name'] ?? "");
header("Content-Type: text/html; charset=UTF-8");

if ($course_name === "") { exit; }

// DB handle safe
$db = isset($conn) ? $conn : (isset($mysqli) ? $mysqli : null);
if (!$db) { exit; }

// 1) find course_id from courses table
$cid = null;
if ($st = $db->prepare("SELECT id FROM courses WHERE course_name = ? LIMIT 1")) {
    $st->bind_param("s", $course_name);
    $st->execute();
    $rr = $st->get_result();
    $row = $rr ? $rr->fetch_assoc() : null;
    if ($row && isset($row['id'])) {
        $cid = (int)$row['id'];
    }
    $st->close();
}

// 2) load units by course_id or fallback text match
if ($cid !== null) {
    $sql = "SELECT id, name
            FROM units
            WHERE course_id = ?
               OR course_name = ?
            ORDER BY name ASC";
    $st = $db->prepare($sql);
    if (!$st) { exit; }
    $st->bind_param("is", $cid, $course_name);
} else {
    $sql = "SELECT id, name
            FROM units
            WHERE course_name = ?
            ORDER BY name ASC";
    $st = $db->prepare($sql);
    if (!$st) { exit; }
    $st->bind_param("s", $course_name);
}

$st->execute();
$res = $st->get_result();

$printed = [];

if ($res && $res->num_rows) {
    while ($u = $res->fetch_assoc()) {
        $unitName = trim((string)($u['name'] ?? ''));
        if ($unitName === '') continue;

        // duplicate unit names avoid
        $key = mb_strtolower($unitName, 'UTF-8');
        if (isset($printed[$key])) continue;
        $printed[$key] = true;

        echo '<option value="' . htmlspecialchars($unitName, ENT_QUOTES, 'UTF-8') . '">'
           . htmlspecialchars($unitName, ENT_QUOTES, 'UTF-8')
           . '</option>';
    }
}

if (empty($printed)) {
    echo '<option value="">-- No units found --</option>';
}

$st->close();