prepare("UPDATE processes SET name = :name, description = :description WHERE id = :id"); $stmt->bindParam(':name', $name, PDO::PARAM_STR); $stmt->bindParam(':description', $description, PDO::PARAM_STR); $stmt->bindParam(':id', $id, PDO::PARAM_INT); if ($stmt->execute()) { // Handle process steps $submitted_steps = $_POST['steps'] ?? []; $existing_step_ids = []; // Fetch existing steps to identify deletions $stmt_fetch_existing = $pdo->prepare("SELECT id FROM process_steps WHERE process_id = :process_id"); $stmt_fetch_existing->bindParam(':process_id', $id, PDO::PARAM_INT); $stmt_fetch_existing->execute(); $db_existing_step_ids = $stmt_fetch_existing->fetchAll(PDO::FETCH_COLUMN); $steps_to_keep_ids = []; foreach ($submitted_steps as $order => $step) { $step_id = $step['id'] ?? null; $step_title = $step['title'] ?? ''; $step_description = $step['description'] ?? ''; if (!empty($step_title) && !empty($step_description)) { if ($step_id) { // Update existing step $stmt_update_step = $pdo->prepare("UPDATE process_steps SET title = :title, description = :description, step_order = :step_order WHERE id = :id AND process_id = :process_id"); $stmt_update_step->bindParam(':title', $step_title, PDO::PARAM_STR); $stmt_update_step->bindParam(':description', $step_description, PDO::PARAM_STR); $stmt_update_step->bindParam(':step_order', $order, PDO::PARAM_INT); $stmt_update_step->bindParam(':id', $step_id, PDO::PARAM_INT); $stmt_update_step->bindParam(':process_id', $id, PDO::PARAM_INT); $stmt_update_step->execute(); $steps_to_keep_ids[] = $step_id; } else { // Insert new step $stmt_insert_step = $pdo->prepare("INSERT INTO process_steps (process_id, title, description, step_order) VALUES (:process_id, :title, :description, :step_order)"); $stmt_insert_step->bindParam(':process_id', $id, PDO::PARAM_INT); $stmt_insert_step->bindParam(':title', $step_title, PDO::PARAM_STR); $stmt_insert_step->bindParam(':description', $step_description, PDO::PARAM_STR); $stmt_insert_step->bindParam(':step_order', $order, PDO::PARAM_INT); $stmt_insert_step->execute(); } } } // Delete steps that were removed from the form $steps_to_delete = array_diff($db_existing_step_ids, $steps_to_keep_ids); if (!empty($steps_to_delete)) { $placeholders = implode(',', array_fill(0, count($steps_to_delete), '?')); $stmt_delete_steps = $pdo->prepare("DELETE FROM process_steps WHERE process_id = ? AND id IN ($placeholders)"); $stmt_delete_steps->execute(array_merge([$id], $steps_to_delete)); } header('Location: index.php?success=processupdated'); exit(); } else { header('Location: index.php?error=updatefailed'); exit(); } } catch (PDOException $e) { error_log("DB Error: " . $e->getMessage()); header('Location: index.php?error=dberror'); exit(); } } else { header('Location: index.php?error=emptyfields'); exit(); } } else { header('Location: index.php?error=invalidrequest'); exit(); }