<?php
require __DIR__ . '/../config.php';
require __DIR__ . '/auth.php';
requireLogin();

/*******************************************************************************
 * Konfiguration
 ******************************************************************************/
$cacheFile   = __DIR__ . '/tts_models.json';
$wavDirFs    = '/var/www/html/WAV/';
$wavDirUrl   = '/WAV/';
$ttsScript   = '/var/www/html/skripts_webseite/PythonTTS2.sh';

$error = '';
$outputFile = '';
$outputFileName = '';
$models = [];

/*******************************************************************************
 * Sprachmodelle aus Cache laden
 ******************************************************************************/
if (!file_exists($cacheFile)) {
    $error = 'Sprachmodell-Cache nicht vorhanden.';
} else {
    $cache = json_decode(file_get_contents($cacheFile), true);
    if (!isset($cache['models']) || !is_array($cache['models'])) {
        $error = 'Sprachmodell-Cache ist ungültig.';
    } else {
        $models = $cache['models'];
    }
}

/*******************************************************************************
 * POST-Verarbeitung
 ******************************************************************************/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$error) {

    $text  = trim($_POST['tts_text'] ?? '');
    $model = trim($_POST['tts_model'] ?? '');

    if ($text === '') {
        $error = 'Kein Text eingegeben.';
    }

    // Modell validieren gegen Cache
    $allowedModels = array_column($models, 'id');
    if ($model === '' || !in_array($model, $allowedModels, true)) {
        $error = 'Ungültiges oder fehlendes Sprachmodell.';
    }

    if (!$error) {
        $outputFileName = 'tts_' . time() . '.wav';
        $wavFileFs  = $wavDirFs . $outputFileName;
        $wavFileUrl = $wavDirUrl . $outputFileName;

        $cmd = escapeshellcmd($ttsScript) . ' '
             . escapeshellarg($model) . ' '
             . escapeshellarg($text) . ' '
             . escapeshellarg($wavFileFs);

        exec($cmd . ' 2>&1', $execOutput, $ret);

        if ($ret === 0 && file_exists($wavFileFs)) {
            $outputFile = $wavFileUrl;
        } else {
            $error = 'TTS-Generierung fehlgeschlagen.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>TTS</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:24px;
}

.box{
    background:var(--panel);
    border:1px solid var(--border);
    padding:20px;
    max-width:900px;
}

h2{margin-top:0;color:var(--accent)}

textarea, select{
    width:100%;
    background:#0f1420;
    color:var(--text);
    border:1px solid var(--border);
    padding:10px;
    font-size:14px;
}

textarea{min-height:120px}

button{
    margin-top:14px;
    padding:8px 20px;
    background:#1c2130;
    border:1px solid var(--border);
    color:var(--text);
    cursor:pointer;
}

button:hover{border-color:var(--accent)}

.error{margin-top:12px;color:var(--error)}
audio{margin-top:16px;width:100%}
</style>
</head>

<body>

<div class="box">
    <h2>Text-to-Speech</h2>

    <form method="post">
        <label>Sprachmodell</label>
        <select name="tts_model" required>
            <option value="">– auswählen –</option>
            <?php foreach ($models as $m): ?>
                <option value="<?= htmlspecialchars($m['id']) ?>"
                    <?= isset($model) && $model === $m['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($m['label']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <br><br>

        <textarea name="tts_text" placeholder="Text eingeben..."><?= 
            htmlspecialchars($text ?? 'Guten Morgen, es ist Acht Uhr.') 
        ?></textarea>

        <button type="submit">Abspielen</button>
    </form>

    <?php if ($error): ?>
        <div class="error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <?php if ($outputFile): ?>
        <audio controls autoplay>
            <source src="<?= htmlspecialchars($outputFile) ?>" type="audio/wav">
        </audio>
    <?php endif; ?>
</div>

</body>
</html>
