<?php
// get_course.php
include('../includes/db.php');
header('Content-Type: application/json');

$id = (int)($_POST['id'] ?? 0);
$out = ['error' => true];
if ($id <= 0) { echo json_encode($out); exit; }

$q = $conn->prepare("SELECT id, status, code, course_name, duration, description, course_description, image FROM courses WHERE id=? LIMIT 1");
$q->bind_param("i", $id); $q->execute();
$course = $q->get_result()->fetch_assoc();
$q->close();
if (!$course) { echo json_encode($out); exit; }

$image_url = !empty($course['image']) ? ("../uploads/courses/".$course['image']) : "../assets/no-image.png";

/* modules from normalized table */
$mods = [];
$m = $conn->prepare("SELECT title FROM course_modules WHERE course_id=? ORDER BY sort_order, id");
$m->bind_param("i", $id); $m->execute();
$r = $m->get_result();
while ($row = $r->fetch_assoc()) { $mods[] = $row['title']; }
$m->close();

/* bundle children */
$bundle_ids = [];
$c = $conn->prepare("SELECT child_id FROM course_children WHERE parent_id=? ORDER BY sort_order, child_id");
$c->bind_param("i", $id); $c->execute();
$cr = $c->get_result();
while ($row = $cr->fetch_assoc()) { $bundle_ids[] = (int)$row['child_id']; }
$c->close();

$type = count($bundle_ids) ? 'bundle' : 'single';

$out = [
  'error' => false,
  'id'    => (int)$course['id'],
  'status'=> $course['status'],
  'code'  => $course['code'],
  'course_name' => $course['course_name'],
  'duration'    => (int)$course['duration'],
  'description' => $course['description'],
  'course_description' => $course['course_description'],
  'image_url'   => $image_url,
  'type'        => $type,
  'modules'       => implode(', ', $mods),  // optional (text)
  'modules_array' => $mods,                 // used by edit modal to render rows
  'bundle_ids'    => $bundle_ids
];
echo json_encode($out);
