<?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', 'echo', 'fable', 'onyx', 'nova', 'shimmer', 'coral', 'sage', 'verse', 'marin', 'cedar'];
$openaiModels = ['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts'];
?>
<!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 textarea {
    width: 100%;
    background: #0f1420;
    color: var(--text);
    border: 1px solid var(--border);
    padding: 10px;
    font-size: 14px;
    border-radius: 6px;
}
.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">
        <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}}, {{datum}}, {{temperatur}}, {{wetter}}, {{wetter_tag}} sowie benutzerdefinierte.</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">
                    <?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>

        <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');

    function toggleProvider() {
        var p = provider.value;
        piperOpts.hidden = p !== 'piper';
        openaiOpts.hidden = p !== 'openai';
    }
    provider.addEventListener('change', toggleProvider);
    toggleProvider();

    source.addEventListener('change', function() {
        var opt = source.options[source.selectedIndex];
        if (opt && opt.value && opt.value.indexOf('wecker-') === 0 && opt.dataset.sprachtext !== undefined) {
            ttsText.value = opt.dataset.sprachtext;
        }
    });

    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>
