'Unauthorized']); exit; } $body = json_decode(file_get_contents('php://input'), true); $action = $body['action'] ?? ''; try { switch ($action) { // ── CREATE ──────────────────────────────────────────────────── case 'create': { $title = trim($body['title'] ?? ''); $desc = trim($body['description'] ?? ''); if (!$title) { echo json_encode(['error' => 'Title is required']); exit; } $maxOrder = $pdo->query(\"SELECT COALESCE(MAX(sort_order),0) FROM training_items\")->fetchColumn(); $stmt = $pdo->prepare(\"INSERT INTO training_items (title, description, sort_order) VALUES (?, ?, ?)\"); $stmt->execute([$title, $desc ?: null, (int)$maxOrder + 1]); echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]); break; } // ── UPDATE ──────────────────────────────────────────────────── case 'update': { $id = (int)($body['id'] ?? 0); $title = trim($body['title'] ?? ''); $desc = trim($body['description'] ?? ''); if (!$id || !$title) { echo json_encode(['error' => 'ID and title are required']); exit; } $stmt = $pdo->prepare(\"UPDATE training_items SET title=?, description=?, updated_at=NOW() WHERE id=?\"); $stmt->execute([$title, $desc ?: null, $id]); echo json_encode(['success' => true]); break; } // ── DELETE ──────────────────────────────────────────────────── case 'delete': { $id = (int)($body['id'] ?? 0); if (!$id) { echo json_encode(['error' => 'ID required']); exit; } $pdo->prepare(\"DELETE FROM training_items WHERE id=?\")->execute([$id]); echo json_encode(['success' => true]); break; } // ── REORDER ─────────────────────────────────────────────────── case 'reorder': { $ids = $body['ids'] ?? []; if (!is_array($ids)) { echo json_encode(['error' => 'IDs must be an array']); exit; } $stmt = $pdo->prepare(\"UPDATE training_items SET sort_order=? WHERE id=?\"); foreach ($ids as $i => $id) { $stmt->execute([$i + 1, (int)$id]); } echo json_encode(['success' => true]); break; } default: echo json_encode(['error' => 'Unknown action']); } } catch (PDOException $e) { http_response_code(500); echo json_encode(['error' => 'Database error: ' . $e->getMessage()]); }