37338-vm/_update_training_checklist_status.php
2026-01-10 17:22:42 +00:00

81 lines
2.5 KiB
PHP

<?php
require_once 'db/config.php';
session_start();
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['success' => 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()]);
}
?>