<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/auth.php';
function_admin_login_erfordern();

require_once FUNCTIONS_ROOT . '/functions_wecker.php';
require_once FUNCTIONS_ROOT . '/functions_common.php';

$weckerListe = function_wecker_hole_alle();
$ttsModels  = function_tts_models_laden();

$openaiVoices = ['alloy', 'ash', 'ballad', 'echo', 'fable', 'onyx', 'nova', 'shimmer', 'coral', 'sage', 'verse', 'marin', 'cedar'];
$openaiModels = ['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts', 'gpt-4o-mini-tts-2025-12-15'];
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TTS für Wecker (Debug)</title>
<style>
:root { --bg:#0f1115; --panel:#151922; --border:#2a2f3a; --text:#e6e6e6; --accent:#4da3ff; --error:#ff6b6b; }
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); font-family: system-ui, sans-serif; padding: 20px; }
h2 { margin-top: 0; color: var(--accent); }
.box { background: var(--panel); border: 1px solid var(--border); padding: 20px; max-width: 700px; border-radius: 8px; margin-bottom: 16px; }
.form-row { margin-bottom: 14px; }
.form-row label { display: block; margin-bottom: 4px; font-size: 0.9rem; color: var(--text); }
.form-row select,
.form-row input[type="text"],
.form-row input[type="password"],
.form-row input[type="number"],
.form-row textarea {
    width: 100%;
    background: #0f1420;
    color: var(--text);
    border: 1px solid var(--border);
    padding: 10px;
    font-size: 14px;
    border-radius: 6px;
}
.form-row input[type="number"] { max-width: 8rem; }
.form-row textarea { min-height: 100px; resize: vertical; }
.form-row small { display: block; margin-top: 4px; color: #888; font-size: 0.85rem; }
.provider-options { margin-left: 12px; margin-top: 8px; }
.provider-options[hidden] { display: none !important; }
button[type="submit"] {
    margin-top: 12px;
    padding: 10px 24px;
    background: #1c2130;
    border: 1px solid var(--border);
    color: var(--text);
    cursor: pointer;
    border-radius: 6px;
    font-size: 1rem;
}
button[type="submit"]:hover { border-color: var(--accent); }
button[type="submit"]:disabled { opacity: 0.6; cursor: not-allowed; }
.error { margin-top: 12px; padding: 10px; background: rgba(255,107,107,0.15); color: var(--error); border-radius: 6px; }
.audio-wrap { margin-top: 16px; }
.audio-wrap audio { width: 100%; margin-top: 8px; }
</style>
</head>
<body>

<div class="box">
    <h2>TTS für Wecker – manuell erzeugen</h2>
    <p>Anbieter, Stimme und Modell wählen und TTS aus Wecker-Sprachtext oder Freitext erzeugen. Platzhalter (z. B. {{name}}) werden ersetzt.</p>

    <form id="ttsForm">
        <input type="hidden" name="id" id="weckerIdInput" value="">
        <div class="form-row">
            <label>Quelle</label>
            <select id="source">
                <option value="text">Freitext (unten eingeben)</option>
                <?php foreach ($weckerListe as $w): ?>
                <option value="wecker-<?= (int)$w['id'] ?>" data-sprachtext="<?= htmlspecialchars($w['sprachtext'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                    Wecker <?= (int)$w['id'] ?> – <?= htmlspecialchars(mb_substr($w['sprachtext'] ?? '', 0, 40)) ?><?= mb_strlen($w['sprachtext'] ?? '') > 40 ? '…' : '' ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-row">
            <label>Text (wird bei Wecker-Auswahl überschrieben)</label>
            <textarea id="ttsText" name="text" placeholder="z.B. Guten Morgen {{name}}, es ist {{uhrzeit}} Uhr."><?= htmlspecialchars('Guten Morgen {{name}}, es ist {{uhrzeit}} Uhr.') ?></textarea>
            <small>Platzhalter: {{name}}, {{uhrzeit}}, {{weckzeit}}, {{datum}}, {{temperatur}}, {{wetter}}, {{wetter_tag}} sowie benutzerdefinierte. Bei Wecker-Auswahl wird {{weckzeit}} mit der Weckzeit ersetzt.</small>
        </div>

        <div class="form-row">
            <label>Anbieter</label>
            <select id="provider" name="tts_provider">
                <option value="piper">Piper (lokal)</option>
                <option value="openai">OpenAI (API)</option>
            </select>
        </div>

        <div id="piperOptions" class="provider-options">
            <div class="form-row">
                <label>Sprachmodell (Piper)</label>
                <select name="tts_modell">
                    <?php foreach ($ttsModels as $m): ?>
                    <option value="<?= htmlspecialchars($m['id'] ?? '') ?>"><?= htmlspecialchars($m['label'] ?? $m['id'] ?? '') ?></option>
                    <?php endforeach; ?>
                    <?php if (empty($ttsModels)): ?>
                    <option value="de_DE-thorsten-high">de_DE-thorsten-high (Fallback)</option>
                    <?php endif; ?>
                </select>
            </div>
        </div>

        <div id="openaiOptions" class="provider-options" hidden>
            <div class="form-row">
                <label>OpenAI API-Key (leer = aus Einstellungen)</label>
                <input type="password" name="tts_openai_api_key" placeholder="sk-…" autocomplete="off">
            </div>
            <div class="form-row">
                <label>Modell</label>
                <select name="tts_openai_model" id="openaiModel">
                    <?php foreach ($openaiModels as $mo): ?>
                    <option value="<?= htmlspecialchars($mo) ?>"><?= htmlspecialchars($mo) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-row">
                <label>Stimme</label>
                <select name="tts_openai_voice">
                    <?php foreach ($openaiVoices as $v): ?>
                    <option value="<?= htmlspecialchars($v) ?>"><?= htmlspecialchars($v) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-row">
                <label for="openaiSpeed">Geschwindigkeit (0,25 – 4,0)</label>
                <input type="number" id="openaiSpeed" name="tts_openai_speed" min="0.25" max="4" step="0.05" value="1" placeholder="1">
                <small>Standard: 1. Schneller = höherer Wert. Ausgabe immer MP3.</small>
            </div>
            <div id="openaiInstructionsRow" class="form-row" style="display:none;">
                <label for="openaiInstructions">Instructions (nur gpt-4o-mini-tts)</label>
                <textarea id="openaiInstructions" name="tts_openai_instructions" rows="3" placeholder="z.B. Leise und entspannt sprechen, leichter Flüsterton …"></textarea>
                <small>Steuert Tonfall, Tempo, Flüstern, Emotion. Nur bei Modell gpt-4o-mini-tts.</small>
            </div>
        </div>

        <button type="submit" id="btnSubmit">TTS erzeugen</button>
    </form>

    <div id="message" class="error" style="display:none;"></div>
    <div id="audioWrap" class="audio-wrap" style="display:none;">
        <p>Erzeugt. Abspielen:</p>
        <audio id="audioPlayer" controls></audio>
    </div>
</div>

<script>
(function() {
    var form = document.getElementById('ttsForm');
    var source = document.getElementById('source');
    var ttsText = document.getElementById('ttsText');
    var provider = document.getElementById('provider');
    var piperOpts = document.getElementById('piperOptions');
    var openaiOpts = document.getElementById('openaiOptions');
    var message = document.getElementById('message');
    var audioWrap = document.getElementById('audioWrap');
    var audioPlayer = document.getElementById('audioPlayer');
    var btnSubmit = document.getElementById('btnSubmit');

    var openaiModel = document.getElementById('openaiModel');
    var openaiInstructionsRow = document.getElementById('openaiInstructionsRow');

    function toggleProvider() {
        var p = provider.value;
        piperOpts.hidden = p !== 'piper';
        openaiOpts.hidden = p !== 'openai';
        if (p === 'openai') toggleGpt4oInstructions();
    }
    function toggleGpt4oInstructions() {
        if (!openaiModel || !openaiInstructionsRow) return;
        var m = (openaiModel.value || '').toLowerCase();
        openaiInstructionsRow.style.display = (m.indexOf('gpt-4o-mini-tts') !== -1) ? '' : 'none';
    }
    provider.addEventListener('change', toggleProvider);
    if (openaiModel) openaiModel.addEventListener('change', toggleGpt4oInstructions);
    toggleProvider();

    var weckerIdInput = document.getElementById('weckerIdInput');
    function updateWeckerId() {
        var opt = source.options[source.selectedIndex];
        var val = opt && opt.value ? opt.value : '';
        if (val.indexOf('wecker-') === 0) {
            var id = val.replace('wecker-', '');
            if (weckerIdInput) weckerIdInput.value = id;
            if (opt.dataset.sprachtext !== undefined) ttsText.value = opt.dataset.sprachtext;
        } else {
            if (weckerIdInput) weckerIdInput.value = '';
        }
    }
    source.addEventListener('change', updateWeckerId);
    updateWeckerId();

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        message.style.display = 'none';
        audioWrap.style.display = 'none';
        btnSubmit.disabled = true;

        var fd = new FormData(form);
        fd.set('action', 'generate');
        fd.set('text', ttsText.value.trim());

        fetch('../api_tts.php', { method: 'POST', body: fd })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                btnSubmit.disabled = false;
                if (data.ok && data.url) {
                    audioPlayer.src = data.url;
                    audioWrap.style.display = 'block';
                    message.style.display = 'none';
                } else {
                    message.textContent = data.error || 'Unbekannter Fehler';
                    message.style.display = 'block';
                }
            })
            .catch(function(err) {
                btnSubmit.disabled = false;
                message.textContent = 'Netzwerkfehler: ' + (err.message || err);
                message.style.display = 'block';
            });
    });
})();
</script>

</body>
</html>
