<?php
// Recon parser for the LearnDash export. Read-only analysis.
$dir = __DIR__;
$load = fn ($f) => json_decode(file_get_contents("$dir/$f"), true);
$courses = $load('courses.json');
$lessons = $load('lessons.json');
$topics  = $load('topics.json');

function videos(string $html): array {
    $out = [];
    if (preg_match_all('/media-id=["\']([A-Za-z0-9]{8,12})["\']/', $html, $m)) foreach ($m[1] as $x) $out[] = "wistia:$x";
    if (preg_match_all('#wistia\.com/embed/(?:medias/)?([A-Za-z0-9]{8,12})#', $html, $m)) foreach ($m[1] as $x) $out[] = "wistia:$x";
    if (preg_match_all('#youtu\.be/([A-Za-z0-9_-]{6,})#', $html, $m)) foreach ($m[1] as $x) $out[] = "yt:$x";
    if (preg_match_all('#youtube\.com/watch\?v=([A-Za-z0-9_-]{6,})#', $html, $m)) foreach ($m[1] as $x) $out[] = "yt:$x";
    if (preg_match_all('#"video_id":"([A-Za-z0-9_-]{6,})"#', $html, $m)) foreach ($m[1] as $x) $out[] = "yt:$x";
    return array_values(array_unique($out));
}
$txt = fn ($v) => trim(html_entity_decode(strip_tags(is_array($v) ? ($v['rendered'] ?? $v['raw'] ?? '') : (string) $v)));
$keys = fn ($a) => implode(', ', array_keys($a));

echo "### COURSE ITEM KEYS\n", $keys($courses[0]), "\n\n";
echo "### LESSON ITEM KEYS\n", $keys($lessons[0]), "\n\n";

echo "### COURSES (".count($courses).")\n";
foreach ($courses as $c) {
    $body = $c['content']['raw'] ?? $c['content']['rendered'] ?? '';
    printf("- #%d  %-55s feat_media=%s  bodyLen=%d  vids=%s\n",
        $c['id'], substr($txt($c['title']),0,55), $c['featured_media'] ?? '-', strlen($body), implode(',', videos($body)) ?: '-');
}

$dump = function ($label, $items) use ($txt) {
    echo "\n### ".strtoupper($label)." (".count($items).")\n";
    foreach ($items as $it) {
        $body = $it['content']['raw'] ?? $it['content']['rendered'] ?? '';
        $course = $it['course'] ?? ($it['meta']['course_id'] ?? ($it['ld_course_steps_count'] ?? '?'));
        $mats = (!empty($it['materials']) || stripos($body,'materials')!==false) ? 'Y' : '-';
        printf("- #%-5d course=%-6s vids=%-26s mat=%s  %s\n",
            $it['id'], is_scalar($course)?$course:'?', implode(',', videos($body)) ?: '-', $mats, substr($txt($it['title']),0,48));
    }
};
$dump('lessons', $lessons);
$dump('topics', $topics);

// show the linkage fields available on a lesson (to map lesson->course)
echo "\n### LESSON LINKAGE SAMPLE (id 2000)\n";
foreach ($lessons as $l) if ($l['id']==2000) {
    foreach (['id','course','lesson','menu_order','parent'] as $k) if (isset($l[$k])) echo "  $k=".(is_scalar($l[$k])?$l[$k]:json_encode($l[$k]))."\n";
    if (isset($l['_links']['https://learndash.com/course'])) echo "  course_link=".json_encode($l['_links']['https://learndash.com/course'])."\n";
}
