false, 'error' => 'Unauthorized']); exit; } if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'Method Not Allowed']); exit; } $inputJSON = file_get_contents('php://input'); $input = json_decode($inputJSON, true); if (json_last_error() !== JSON_ERROR_NONE) { http_response_code(400); echo json_encode(['error' => 'Invalid JSON']); exit; } $instanceId = $input['instance_id'] ?? null; $taskCode = $input['task_code'] ?? null; $isChecked = $input['is_checked'] ?? null; if (!$instanceId || !$taskCode || $isChecked === null) { http_response_code(400); echo json_encode(['error' => 'Missing required parameters: instance_id, task_code, is_checked']); exit; } try { $pdo = db(); // Get current data_json $stmt = $pdo->prepare("SELECT data_json FROM process_instances WHERE id = ?"); $stmt->execute([$instanceId]); $currentDataJson = $stmt->fetchColumn(); $data = $currentDataJson ? json_decode($currentDataJson, true) : []; // Update the specific task status $data[$taskCode] = (bool)$isChecked; $newDataJson = json_encode($data); // Save new data_json and update timestamp $stmt = $pdo->prepare("UPDATE process_instances SET data_json = ?, lastActivityAt = CURRENT_TIMESTAMP WHERE id = ?"); $success = $stmt->execute([$newDataJson, $instanceId]); if ($success) { // Calculate progress $stmt = $pdo->prepare("SELECT pd.definition_json FROM process_definitions pd JOIN process_instances pi ON pd.id = pi.process_definition_id WHERE pi.id = ?"); $stmt->execute([$instanceId]); $definitionJson = $stmt->fetchColumn(); $definition = json_decode($definitionJson, true); $totalTasks = count($definition['tasks'] ?? []); $completedTasks = count(array_filter($data)); echo json_encode([ 'success' => true, 'message' => 'Status updated successfully.', 'progress' => [ 'completed' => $completedTasks, 'total' => $totalTasks ], 'lastActivityAt' => date('d/m/y') ]); } else { http_response_code(500); echo json_encode(['error' => 'Failed to update status.']); } } catch (PDOException $e) { http_response_code(500); echo json_encode(['error' => 'Database error: ' . $e->getMessage()]); } ?>