<?php
// add_course.php
include('../includes/db.php');

try {
    $status   = $_POST['status'] ?? 'Active';
    $type     = $_POST['type']   ?? 'single'; // 'single'|'bundle'
    $code     = trim($_POST['code'] ?? '');
    $name     = trim($_POST['course_name'] ?? '');
    $duration = (int)($_POST['duration'] ?? 0);
    $desc     = trim($_POST['description'] ?? '');
    $cdesc    = trim($_POST['course_description'] ?? '');

    if ($name === '' || $code === '') throw new Exception("Missing required fields.");

    // Image upload (optional)
    $image = null;
    if (!empty($_FILES['image']['name']) && is_uploaded_file($_FILES['image']['tmp_name'])) {
        @mkdir('../uploads/courses', 0775, true);
        $fname = time().'_'.preg_replace('/[^A-Za-z0-9._-]+/','_', $_FILES['image']['name']);
        $dest  = "../uploads/courses/".$fname;
        if (!move_uploaded_file($_FILES['image']['tmp_name'], $dest)) throw new Exception("Image upload failed.");
        $image = $fname;
    }

    // Insert course
    $stmt = $conn->prepare("INSERT INTO courses(status, code, course_name, duration, description, course_description, image)
                            VALUES(?,?,?,?,?,?,?)");
    $stmt->bind_param("sssisss", $status, $code, $name, $duration, $desc, $cdesc, $image);
    if (!$stmt->execute()) throw new Exception("Insert course failed.");
    $course_id = $stmt->insert_id;
    $stmt->close();

    if ($type === 'single') {
        // Save modules into normalized table
        $mods = [];
        if (!empty($_POST['modules']) && is_array($_POST['modules'])) {
            $mods = $_POST['modules'];
        } elseif (!empty($_POST['modules']) && is_string($_POST['modules'])) {
            $mods = preg_split('/[,;\r\n]+/', $_POST['modules']);
        }
        $i = 1;
        if (!empty($mods)) {
            $ins = $conn->prepare("INSERT INTO course_modules(course_id, title, sort_order) VALUES(?,?,?)");
            foreach ($mods as $m) {
                $t = trim((string)$m);
                if ($t === '') continue;
                $order = $i++; // bind_param needs a variable (by reference)
                $ins->bind_param("isi", $course_id, $t, $order);
                $ins->execute();
            }
            $ins->close();
        }
    } else { // bundle
        $children = $_POST['bundle_courses'] ?? [];
        if (!is_array($children)) $children = [];
        $i = 1;
        if (!empty($children)) {
            $ins = $conn->prepare("INSERT INTO course_children(parent_id, child_id, sort_order) VALUES(?,?,?)");
            foreach ($children as $cid) {
                $child_id = (int)$cid;
                if ($child_id <= 0) continue;
                $order = $i++;
                $ins->bind_param("iii", $course_id, $child_id, $order);
                $ins->execute();
            }
            $ins->close();
        }
    }

    echo "success";
} catch (Throwable $e) {
    echo $e->getMessage();
}
