<?php
require __DIR__ . '/../config.php';
require FUNCTIONS_ROOT . '/functions_db.php';
require FUNCTIONS_ROOT . '/functions_wecker.php';
require FUNCTIONS_ROOT . '/functions_common.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    function_json_antwort(true, ['einstellungen' => function_einstellungen_fuer_api()]);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    function_json_antwort(false, [], 'Method not allowed');
}

$tts_provider = trim($_POST['tts_provider'] ?? '');
$tts_modell = trim($_POST['tts_modell'] ?? '');
$tts_openai_api_key = $_POST['tts_openai_api_key'] ?? '';
$tts_openai_model = trim($_POST['tts_openai_model'] ?? '');
$tts_openai_voice = trim($_POST['tts_openai_voice'] ?? '');
$zeitzone = trim($_POST['zeitzone'] ?? '');
$tts_name = trim($_POST['tts_name'] ?? '');
$wetter_ort = trim($_POST['wetter_ort'] ?? '');
$sleep_mode_sekunden = trim($_POST['sleep_mode_sekunden'] ?? '');
$accent_color = trim($_POST['accent_color'] ?? '');

if (in_array($tts_provider, ['piper', 'openai'], true)) {
    function_einstellung_setzen('tts_provider', $tts_provider);
}
if ($tts_modell !== '') {
    function_einstellung_setzen('tts_modell', $tts_modell);
}
if (isset($_POST['tts_openai_api_key'])) {
    $v = is_string($tts_openai_api_key) ? trim($tts_openai_api_key) : '';
    if ($v !== '' && $v !== '********') {
        $toStore = function_exists('function_encrypt_secret') ? function_encrypt_secret($v) : $v;
        function_einstellung_setzen('tts_openai_api_key', $toStore);
    }
}
if (in_array($tts_openai_model, ['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts', 'gpt-4o-mini-tts-2025-12-15'], true)) {
    function_einstellung_setzen('tts_openai_model', $tts_openai_model);
}
$allowedVoices = ['alloy', 'ash', 'ballad', 'echo', 'fable', 'onyx', 'nova', 'shimmer', 'coral', 'sage', 'verse', 'marin', 'cedar'];
if ($tts_openai_voice !== '' && in_array($tts_openai_voice, $allowedVoices, true)) {
    function_einstellung_setzen('tts_openai_voice', $tts_openai_voice);
}
if ($zeitzone !== '') {
    function_einstellung_setzen('zeitzone', $zeitzone);
}
function_einstellung_setzen('tts_name', $tts_name);
function_einstellung_setzen('wetter_ort', $wetter_ort);
if ($sleep_mode_sekunden !== '') {
    $sleep_mode_sekunden = max(0, min(86400, (int) $sleep_mode_sekunden)); // 0 = aus, max 24h
    function_einstellung_setzen('sleep_mode_sekunden', (string) $sleep_mode_sekunden);
}
if (preg_match('/^#[0-9a-fA-F]{3}$|^#[0-9a-fA-F]{6}$/', $accent_color) || $accent_color === '') {
    function_einstellung_setzen('accent_color', $accent_color);
}

function_json_antwort(true);
