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

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

    if ($id <= 0) throw new Exception("Invalid ID");
    if ($name === '' || $code === '') throw new Exception("Missing required fields");

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

    if ($newImage) {
        $sql = "UPDATE courses SET status=?, code=?, course_name=?, duration=?, description=?, course_description=?, image=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        //             s     s     s     i     s           s            s      i
        $stmt->bind_param("sssisssi", $status, $code, $name, $duration, $desc, $cdesc, $newImage, $id);
    } else {
        $sql = "UPDATE courses SET status=?, code=?, course_name=?, duration=?, description=?, course_description=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        //             s     s     s     i     s           s       i
        $stmt->bind_param("sssissi",  $status, $code, $name, $duration, $desc, $cdesc, $id);
    }

    if (!$stmt->execute()) throw new Exception("Update failed");
    $stmt->close();

    // Reset relations then reinsert
    $del1 = $conn->prepare("DELETE FROM course_modules WHERE course_id=?");
    $del1->bind_param("i", $id); $del1->execute(); $del1->close();

    $del2 = $conn->prepare("DELETE FROM course_children WHERE parent_id=?");
    $del2->bind_param("i", $id); $del2->execute(); $del2->close();

    if ($type === 'single') {
        $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++;
                $ins->bind_param("isi", $id, $t, $order);
                $ins->execute();
            }
            $ins->close();
        }
    } else {
        $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", $id, $child_id, $order);
                $ins->execute();
            }
            $ins->close();
        }
    }

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