<?php
// ajax/fetch_modules_from_courses.php
// Returns JSON: { ok: true, modules: [flat], groups: [{course_id,course_name,modules:[]}, ...], debug: {...} }
header('Content-Type: application/json; charset=utf-8');

@ini_set('display_errors', '0');
@ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_WARNING);
if (function_exists('ob_get_length')) { while (ob_get_level()) { ob_end_clean(); } }

$debug = ['path' => [], 'legacy_bundle_text' => null];

try {
    // DB
    $db_ok = @include_once __DIR__ . '/../includes/db.php';
    if (!$db_ok || !isset($conn) || !($conn instanceof mysqli)) {
        $conn = new mysqli("localhost","root","","edencamp_eden_exam");
        if ($conn->connect_error) { throw new Exception("DB Error: ".$conn->connect_error); }
        $conn->set_charset("utf8mb4");
    }

    $course_id = (int)($_GET['course_id'] ?? $_POST['course_id'] ?? 0);
    if ($course_id <= 0) { echo json_encode(['ok'=>false,'modules'=>[],'groups'=>[],'debug'=>['reason'=>'bad course_id']]); exit; }

    // helper: get modules for a course (normalized table first, then legacy text)
    $get_modules_for = function(mysqli $conn, int $cid, array &$debug): array {
        $mods = [];

        // 1) normalized table
        if ($st = $conn->prepare("SELECT title FROM course_modules WHERE course_id=? ORDER BY sort_order, id")) {
            $st->bind_param("i", $cid);
            if ($st->execute()) {
                $rs = $st->get_result();
                while ($row = $rs->fetch_assoc()) { $mods[] = $row['title']; }
            }
            $st->close();
        } else {
            $debug['path'][] = "prepare_failed_course_modules_for_$cid";
        }

        // 2) legacy text fallback
        if (!$mods) {
            if ($st = $conn->prepare("SELECT modules FROM courses WHERE id=? LIMIT 1")) {
                $st->bind_param("i", $cid);
                if ($st->execute()) {
                    $row = $st->get_result()->fetch_assoc();
                    if ($row) {
                        $s = (string)($row['modules'] ?? '');
                        if ($s !== '') {
                            $parts = preg_split('/[,;\r\n]+/', $s);
                            foreach ($parts as $p) {
                                $p = trim($p);
                                if ($p !== '') $mods[] = $p;
                            }
                        }
                    }
                }
                $st->close();
            } else {
                $debug['path'][] = "prepare_failed_courses.modules_for_$cid";
            }
        }

        return $mods;
    };

    // parent row (name + legacy bundle text)
    $parent_name = '';
    $legacy_bundle_text = '';
    if ($st = $conn->prepare("SELECT course_name, bundle_courses FROM courses WHERE id=? LIMIT 1")) {
        $st->bind_param("i", $course_id);
        if ($st->execute()) {
            $row = $st->get_result()->fetch_assoc();
            if ($row) {
                $parent_name = trim((string)$row['course_name']);
                $legacy_bundle_text = (string)($row['bundle_courses'] ?? '');
            }
        }
        $st->close();
    } else {
        $debug['path'][] = 'prepare_failed_parent_row';
    }
    $debug['legacy_bundle_text'] = $legacy_bundle_text;

    // groups
    $groups = [];

    // 1) parent
    $pmods = $get_modules_for($conn, $course_id, $debug);
    $groups[] = [
        'course_id'   => $course_id,
        'course_name' => ($parent_name !== '' ? $parent_name : 'Main Course'),
        'modules'     => $pmods
    ];

    // 2) children via normalized table
    $child_rows = 0;
    if ($st = $conn->prepare("
        SELECT ch.child_id, c.course_name
        FROM course_children ch
        JOIN courses c ON c.id = ch.child_id
        WHERE ch.parent_id=?
        ORDER BY ch.sort_order, ch.child_id
    ")) {
        $st->bind_param("i", $course_id);
        if ($st->execute()) {
            $rs = $st->get_result();
            while ($row = $rs->fetch_assoc()) {
                $child_rows++;
                $cid = (int)$row['child_id'];
                $cname = trim((string)$row['course_name']);
                $groups[] = [
                    'course_id'   => $cid,
                    'course_name' => ($cname !== '' ? $cname : "Course #$cid"),
                    'modules'     => $get_modules_for($conn, $cid, $debug)
                ];
            }
        }
        $st->close();
    } else {
        $debug['path'][] = 'prepare_failed_course_children';
    }

    // 3) legacy fallback: courses.bundle_courses (comma-separated ids)
    if ($child_rows === 0 && trim($legacy_bundle_text) !== '') {
        $debug['path'][] = 'using_legacy_bundle_courses';
        $ids = preg_split('/[,;\r\n]+/', $legacy_bundle_text);
        $ids = array_values(array_filter(array_map('intval', $ids), fn($x)=>$x>0));
        if ($ids) {
            // names
            $names = [];
            $in = implode(',', $ids);
            if ($q = $conn->query("SELECT id, course_name FROM courses WHERE id IN ($in)")) {
                while ($c = $q->fetch_assoc()) { $names[(int)$c['id']] = trim((string)$c['course_name']); }
            } else {
                $debug['path'][] = 'query_failed_names_for_legacy_children';
            }
            foreach ($ids as $cid) {
                $groups[] = [
                    'course_id'   => $cid,
                    'course_name' => ($names[$cid] ?? "Course #$cid"),
                    'modules'     => $get_modules_for($conn, $cid, $debug)
                ];
            }
        }
    } else {
        $debug['path'][] = ($child_rows > 0 ? 'used_course_children' : 'no_children_anywhere');
    }

    // flat list
    $flat = [];
    foreach ($groups as $g) foreach ($g['modules'] as $m) $flat[] = $m;

    echo json_encode(['ok'=>true, 'modules'=>$flat, 'groups'=>$groups, 'debug'=>$debug], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    echo json_encode(['ok'=>false, 'modules'=>[], 'groups'=>[], 'error'=>$e->getMessage(), 'debug'=>$debug]);
}
