<?php

// Verify the HTTP method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
	echo json_encode(["success" => false, "error" => "Invalid request method. Only POST is allowed."]);
	exit;
}

// Get the raw POST data
$data = json_decode(file_get_contents("php://input"), true);

// Validate input data
if (!isset($data['run_id']) || !isset($data['timestamp']) || !isset($data['action'])) {
	echo json_encode(["success" => false, "error" => "Missing required fields: 'run_id', 'timestamp', or 'action'."]);
	exit;
}

$runId = intval($data['run_id']);
$timestamp = intval($data['timestamp']);
$action = $data['action'];

// Map actions to status codes
$actionMapping = [
	"start" => 1, // Status "In Progress"
	"dns" => 3,   // Status "Did Not Start"
	"delay" => 4  // Status "Delayed"
];

// Validate action
if (!array_key_exists($action, $actionMapping)) {
	echo json_encode(["success" => false, "error" => "Invalid action. Allowed actions: 'start', 'dns', 'delay'."]);
	exit;
}

// Get the corresponding status code
$status = $actionMapping[$action];

// Update the database
$updateQuery = "UPDATE runs SET real_time = ? WHERE id = ?";
$stmt = $conn->prepare($updateQuery);
$stmt->bind_param("ii", $timestamp, $runId);

if ($stmt->execute()) {
	echo json_encode(["success" => true, "message" => "Run updated successfully."]);
} else {
	echo json_encode(["success" => false, "error" => "Failed to update the run."]);
}

// Close the statement and connection
$stmt->close();
?>