'error', 'message' => 'Unauthorized access']); exit; } $user_role = getUserRole(); if (!in_array($user_role, ['admin', 'superadmin'])) { ob_end_clean(); echo json_encode(['status' => 'error', 'message' => 'Unauthorized access']); exit; } try { $course_id = $_POST['course_id'] ?? null; $course_type = trim($_POST['course_type'] ?? ''); $code = trim($_POST['code'] ?? ''); $date = trim($_POST['date'] ?? ''); $capacity = intval($_POST['capacity'] ?? 0); $cost_members = floatval($_POST['cost_members'] ?? 0); $cost_nonmembers = floatval($_POST['cost_nonmembers'] ?? 0); $instructor = trim($_POST['instructor'] ?? ''); $instructor_email = trim($_POST['instructor_email'] ?? ''); $allowed_types = ['driver_training','bush_mechanics','rescue_recovery','ladies_driver_training']; if (!in_array($course_type, $allowed_types)) { throw new Exception('Invalid course type'); } if (empty($date) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) { throw new Exception('Invalid date format'); } // If code not provided, generate from type + date using ABBR_MMDD format if (empty($code)) { $abbrMap = [ 'driver_training' => 'DRVTRN', 'bush_mechanics' => 'BUSHMEC', 'rescue_recovery' => 'RESREC', 'ladies_driver_training' => 'LADYTRN' ]; $abbr = $abbrMap[$course_type] ?? strtoupper(preg_replace('/[^A-Z0-9]/', '', $course_type)); // ensure abbr fits (reserve 1 char for underscore and 4 for MMDD) $abbr = substr($abbr, 0, 7); $mmdd = date('md', strtotime($date)); $code = strtoupper(substr($abbr . '_' . $mmdd, 0, 12)); } if ($capacity <= 0) { throw new Exception('Capacity must be greater than 0'); } if (empty($instructor)) { throw new Exception('Instructor name is required'); } if ($course_id) { // Update $stmt = $conn->prepare("UPDATE courses SET course_type = ?, code = ?, date = ?, capacity = ?, cost_members = ?, cost_nonmembers = ?, instructor = ?, instructor_email = ? WHERE course_id = ?"); $stmt->bind_param("sssiddssi", $course_type, $code, $date, $capacity, $cost_members, $cost_nonmembers, $instructor, $instructor_email, $course_id); if (!$stmt->execute()) { throw new Exception('Failed to update course: ' . $stmt->error); } $stmt->close(); } else { // Insert - booked defaults to 0 $stmt = $conn->prepare("INSERT INTO courses (course_type, code, date, capacity, booked, cost_members, cost_nonmembers, instructor, instructor_email) VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?)"); $stmt->bind_param("sssiddss", $course_type, $code, $date, $capacity, $cost_members, $cost_nonmembers, $instructor, $instructor_email); if (!$stmt->execute()) { throw new Exception('Failed to create course: ' . $stmt->error); } $course_id = $conn->insert_id; $stmt->close(); } ob_end_clean(); echo json_encode(['status' => 'success', 'message' => $course_id ? 'Course saved successfully' : 'Course created successfully', 'course_id' => $course_id]); } catch (Exception $e) { ob_end_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]); } ?>