false, 'message' => 'Invalid request method']); exit; } try { $pdo = getDBConnection(); $data = json_decode(file_get_contents('php://input'), true); $action = $data['action'] ?? ''; $selection_id = (int)($data['selection_id'] ?? 0); if (!$selection_id) { throw new Exception('Invalid selection ID'); } // Get selection and project details $stmt = $pdo->prepare(" SELECT ps.*, p.status as project_status FROM project_selections ps INNER JOIN projects p ON ps.project_id = p.id WHERE ps.id = ? "); $stmt->execute([$selection_id]); $selection = $stmt->fetch(); if (!$selection) { throw new Exception('Selection not found'); } // Handle different actions switch ($action) { case 'update_status': $new_status = $data['status'] ?? ''; // Validate status transitions $allowed_transitions = [ 'draft' => ['launched'], 'launched' => ['paused', 'closed'], 'paused' => ['launched', 'closed'], 'closed' => [] // Cannot change from closed ]; $current_status = $selection['status']; // Check if project is closed if ($selection['project_status'] === 'closed') { throw new Exception('Cannot change selection status when project is closed'); } // Check if transition is allowed if (!in_array($new_status, $allowed_transitions[$current_status])) { throw new Exception('Invalid status transition'); } // Update status $stmt = $pdo->prepare(" UPDATE project_selections SET status = ?, launched_at = CASE WHEN ? = 'launched' AND launched_at IS NULL THEN NOW() ELSE launched_at END, updated_at = NOW() WHERE id = ? "); $stmt->execute([$new_status, $new_status, $selection_id]); // Log activity $stmt = $pdo->prepare(" INSERT INTO selection_activity_log (selection_id, action, description, performed_by) VALUES (?, ?, ?, ?) "); $stmt->execute([ $selection_id, 'status_changed', "Status changed from {$current_status} to {$new_status}", $_SESSION['admin_id'] ]); echo json_encode([ 'success' => true, 'message' => 'Status updated successfully' ]); break; case 'delete': // Can only delete if draft if ($selection['status'] !== 'draft') { throw new Exception('Can only delete draft selections'); } // Delete selection (cascade will delete criteria and members) $stmt = $pdo->prepare("DELETE FROM project_selections WHERE id = ?"); $stmt->execute([$selection_id]); echo json_encode([ 'success' => true, 'message' => 'Selection deleted successfully' ]); break; default: throw new Exception('Unknown action'); } } catch (Exception $e) { error_log("Selection action error: " . $e->getMessage()); echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); }