<?php

// Function to update the schedule's planned time
function updateSchedulePlannedTime($conn, $scheduleId, $timePlanned) {
	$query = "UPDATE schedule SET time_planned = ? WHERE id = ?";
	$stmt = $conn->prepare($query);

	if (!$stmt) {
		return ["success" => false, "message" => "Failed to prepare statement."];
	}

	// Handle NULL case
	if ($timePlanned === null) {
		$query = "UPDATE schedule SET time_planned = NULL WHERE id = ?";
		$stmt = $conn->prepare($query);
		$stmt->bind_param("i", $scheduleId);
	} else {
		$stmt->bind_param("ii", $timePlanned, $scheduleId);
	}

	if ($stmt->execute()) {
		return ["success" => true, "message" => "Schedule updated successfully."];
	} else {
		return ["success" => false, "message" => "Failed to update schedule."];
	}
}

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	// Get JSON body
	$input = json_decode(file_get_contents("php://input"), true);

	// Validate input
	if (!isset($input['schedule_id']) || !array_key_exists('time_planned', $input)) {
		echo json_encode(["success" => false, "message" => "Missing required fields."]);
		exit();
	}

	$scheduleId = (int)$input['schedule_id'];
	$timePlanned = $input['time_planned'] !== null ? (int)$input['time_planned'] : null;

	// Update the schedule
	$response = updateSchedulePlannedTime($conn, $scheduleId, $timePlanned);

	// Send response
	echo json_encode($response);
} else {
	// Invalid request method
	echo json_encode(["success" => false, "message" => "Invalid request method."]);
}

?>