<?php
// Simple uploader para audios que añade entrada a episodes.json
// Requiere servidor con PHP habilitado. Guarda archivos en ../audio/

function slugify($text) {
    $text = trim($text);
    $replacements = [
        'Á'=>'A','É'=>'E','Í'=>'I','Ó'=>'O','Ú'=>'U','Ñ'=>'N',
        'á'=>'a','é'=>'e','í'=>'i','ó'=>'o','ú'=>'u','ñ'=>'n'
    ];
    $text = strtr($text, $replacements);
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = trim($text, '-');
    $text = strtolower($text);
    $text = preg_replace('~[^-a-z0-9]+~', '', $text);
    return $text;
}

$root = dirname(__DIR__);
$audioDir = $root . DIRECTORY_SEPARATOR . 'audio' . DIRECTORY_SEPARATOR;
$episodesPath = $root . DIRECTORY_SEPARATOR . 'episodes.json';

$message = '';
$ok = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['audio']) || $_FILES['audio']['error'] !== UPLOAD_ERR_OK) {
        $message = 'Error al subir archivo.';
    } else {
        $origName = $_FILES['audio']['name'];
        $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
        $allowed = ['mp3','m4a','ogg'];
        if (!in_array($ext, $allowed)) {
            $message = 'Formato no permitido. Usa MP3, M4A u OGG.';
        } else {
            $safeBase = slugify(pathinfo($origName, PATHINFO_FILENAME));
            $finalName = $safeBase . '.' . $ext;
            $target = $audioDir . $finalName;
            if (!is_dir($audioDir)) {
                @mkdir($audioDir, 0775, true);
            }
            if (move_uploaded_file($_FILES['audio']['tmp_name'], $target)) {
                $title = isset($_POST['title']) && $_POST['title'] !== '' ? trim($_POST['title']) : str_replace('-', ' ', $safeBase);
                $episode = [
                    'title' => $title,
                    'duration' => '',
                    'url' => 'audio/' . $finalName,
                    'sources' => []
                ];

                // Leer episodes.json y agregar entrada si no existe ya
                $list = [];
                if (file_exists($episodesPath)) {
                    $json = file_get_contents($episodesPath);
                    $list = json_decode($json, true);
                    if (!is_array($list)) $list = [];
                }
                // Evitar duplicados por url
                $exists = false;
                foreach ($list as $ep) {
                    if (isset($ep['url']) && $ep['url'] === $episode['url']) { $exists = true; break; }
                }
                if (!$exists) {
                    $list[] = $episode;
                }
                file_put_contents($episodesPath, json_encode($list, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
                $ok = true;
                $message = 'Audio subido y episodio añadido correctamente.';
            } else {
                $message = 'No se pudo guardar el archivo subido.';
            }
        }
    }
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Subir audio</title>
  <style>
    body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background:#f8fafc; color:#111827; }
    .container { max-width: 720px; margin: 40px auto; background: white; padding: 24px; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); }
    .field { margin-bottom: 16px; }
    .label { font-weight: 600; margin-bottom: 8px; display:block; }
    .input, .file { width: 100%; padding: 10px 12px; border:1px solid #e5e7eb; border-radius:8px; }
    .btn-primary { background:#2563eb; color:white; padding:10px 16px; border:none; border-radius:8px; cursor:pointer; }
    .msg { margin-top: 12px; padding: 10px; border-radius: 8px; }
    .msg.ok { background:#ecfdf5; color:#065f46; border:1px solid #10b981; }
    .msg.err { background:#fef2f2; color:#991b1b; border:1px solid #ef4444; }
    .links { margin-top: 16px; display:flex; gap:12px; }
    a.btn-secondary { display:inline-block; padding:10px 16px; border:1px solid #d1d5db; border-radius:8px; color:#111827; text-decoration:none; }
  </style>
  <meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline';">
  <meta http-equiv="Referrer-Policy" content="no-referrer">
</head>
<body>
  <div class="container">
    <h1 style="margin-bottom:16px;">Subir audio</h1>
    <p style="color:#6b7280; margin-bottom:16px;">Sube un archivo MP3, M4A u OGG. Se guardará en <code>audio/</code> y se añadirá a <code>episodes.json</code>.</p>
    <?php if ($message): ?>
      <div class="msg <?php echo $ok ? 'ok' : 'err'; ?>"><?php echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8'); ?></div>
    <?php endif; ?>
    <form method="post" enctype="multipart/form-data">
      <div class="field">
        <label class="label">Título (opcional)</label>
        <input class="input" type="text" name="title" placeholder="Ej: Área de Alsacia">
      </div>
      <div class="field">
        <label class="label">Archivo de audio</label>
        <input class="file" type="file" name="audio" accept="audio/mp3,audio/mpeg,audio/m4a,audio/mp4,audio/ogg" required>
      </div>
      <button class="btn-primary" type="submit">Subir y añadir</button>
    </form>
    <div class="links">
      <a class="btn-secondary" href="../index.html">Volver a inicio</a>
      <a class="btn-secondary" href="../podcasts.html">Ir a podcasts</a>
    </div>
    <p style="color:#6b7280; margin-top:16px; font-size:0.9rem;">Nota: este formulario necesita que el servidor ejecute PHP. En local, con <code>python -m http.server</code>, no funcionará el procesamiento del formulario.</p>
  </div>
</body>
</html>