<?php
header('Content-Type: application/json');

$date  = $_GET['date'] ?? '';
$time  = $_GET['time'] ?? '';
$text  = $_GET['text'] ?? '';
$color = $_GET['color'] ?? 'lightblue';

if (!$date || !$time || !$text) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Missing required parameters"]);
    exit;
}

$date  = preg_replace('/[^0-9\-]/', '', $date);
$time  = preg_replace('/[^0-9\.]/', '', $time);
$text  = strip_tags($text);
$color = strip_tags($color);

$newEvent = [
    "date"  => $date,
    "time"  => $time,
    "text"  => $text,
    "color" => $color
];

$jsonFile = 'dates.json';
$events = [];

if (file_exists($jsonFile)) {
    $data = file_get_contents($jsonFile);
    $events = json_decode($data, true);
    if (!is_array($events)) $events = [];
}

$events[] = $newEvent;

if (file_put_contents($jsonFile, json_encode($events, JSON_PRETTY_PRINT))) {
    echo json_encode(["status" => "success", "message" => "Event saved"]);
} else {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Could not write to file"]);
}
