<?php
/** Nexora VE Networks — Ambientación musical. */
$nexMusicPath = __PATH_CONFIGS__ . 'music.json';
$nexMusicDir = __PATH_TEMPLATE_ROOT__ . 'audio/';

function nexMusicAdminLoad() {
    $cfg = loadConfig('music');
    if (!is_array($cfg)) $cfg = array();
    if (!isset($cfg['settings']) || !is_array($cfg['settings'])) $cfg['settings'] = array();
    if (!isset($cfg['tracks']) || !is_array($cfg['tracks'])) $cfg['tracks'] = array();
    return $cfg;
}
function nexMusicAdminSave($cfg) {
    $path = __PATH_CONFIGS__ . 'music.json';
    $json = json_encode($cfg, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    if ($json === false || @file_put_contents($path, $json . "\n", LOCK_EX) === false) throw new Exception('No se pudo guardar music.json.');
}
function nexMusicAdminText($value, $max=160) {
    $value = trim(strip_tags((string)$value));
    return function_exists('mb_substr') ? mb_substr($value, 0, $max, 'UTF-8') : substr($value, 0, $max);
}
function nexMusicAdminUrl($value) {
    $value = trim((string)$value);
    if ($value === '') return '';
    if (filter_var($value, FILTER_VALIDATE_URL) && preg_match('#^https://#i', $value)) return $value;
    return preg_match('#^[a-zA-Z0-9/_\.\-]+$#', $value) ? $value : '';
}
function nexMusicAdminId() { return 'track-' . substr(md5(uniqid('', true)), 0, 10); }
function nexMusicAdminUpload($field, $id) {
    $uploadDir = __PATH_TEMPLATE_ROOT__ . 'audio/';
    if (empty($_FILES[$field]['tmp_name']) || !is_uploaded_file($_FILES[$field]['tmp_name'])) return '';
    if ((int)$_FILES[$field]['size'] > 25 * 1024 * 1024) throw new Exception('Cada pista puede pesar hasta 25 MB.');
    $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
    $allowed = array('mp3'=>'mp3','ogg'=>'ogg','webm'=>'webm','m4a'=>'m4a');
    if (!isset($allowed[$ext])) throw new Exception('Formatos permitidos: MP3, OGG, WebM y M4A.');
    if (!is_dir($uploadDir) && !@mkdir($uploadDir, 0755, true)) throw new Exception('No se pudo crear la carpeta de audio.');
    $file = preg_replace('/[^a-z0-9_-]/i', '-', $id) . '-' . date('YmdHis') . '.' . $allowed[$ext];
    if (!@move_uploaded_file($_FILES[$field]['tmp_name'], $uploadDir . $file)) throw new Exception('No se pudo almacenar el audio.');
    @chmod($uploadDir . $file, 0644);
    return $file;
}
function nexMusicA($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }

try {
    if (!file_exists($nexMusicPath)) nexMusicAdminSave(array('settings'=>array(), 'tracks'=>array()));
    if (!is_dir($nexMusicDir)) @mkdir($nexMusicDir, 0755, true);
    $cfg = nexMusicAdminLoad();

    if (isset($_POST['music_settings_save'])) {
        $selectedMode = in_array($_POST['source_mode'] ?? '',array('local','youtube','hybrid'),true)?$_POST['source_mode']:'local';
        $selectedYoutubeUrl = nexMusicAdminUrl($_POST['youtube_url'] ?? '');
        if ($selectedMode === 'local' && $selectedYoutubeUrl !== '' && empty($cfg['tracks'])) $selectedMode = 'youtube';
        $cfg['settings'] = array(
            'enabled'=>isset($_POST['enabled']),
            'source_mode'=>$selectedMode,
            'youtube_url'=>$selectedYoutubeUrl,
            'title'=>nexMusicAdminText($_POST['player_title'] ?? '', 80),
            'subtitle'=>nexMusicAdminText($_POST['player_subtitle'] ?? '', 100),
            'initial_volume'=>max(0, min(100, (int)($_POST['initial_volume'] ?? 35))),
            'shuffle'=>isset($_POST['shuffle']),
            'loop'=>isset($_POST['loop']),
            'remember_state'=>isset($_POST['remember_state'])
        );
        nexMusicAdminSave($cfg); message('success', 'Configuración musical actualizada. Fuente activa: ' . ($selectedMode === 'youtube' ? 'YouTube' : ($selectedMode === 'hybrid' ? 'Híbrida' : 'Audio propio')) . '.');
    }

    if (isset($_POST['track_add'])) {
        $title = nexMusicAdminText($_POST['track_title'] ?? '', 100);
        if ($title === '') throw new Exception('El título de la pista es obligatorio.');
        $id = nexMusicAdminId();
        $file = nexMusicAdminUpload('track_file', $id);
        $url = nexMusicAdminUrl($_POST['track_url'] ?? '');
        if ($file === '' && $url === '') throw new Exception('Sube un archivo o indica una URL HTTPS.');
        $cfg['tracks'][] = array('id'=>$id,'enabled'=>true,'order'=>(int)($_POST['track_order'] ?? 100),'realm'=>in_array($_POST['track_realm'] ?? '',array('both','legacy','seasonal'),true)?$_POST['track_realm']:'both','title'=>$title,'artist'=>nexMusicAdminText($_POST['track_artist'] ?? '',80),'file'=>$file,'url'=>$url);
        nexMusicAdminSave($cfg); message('success', 'Pista añadida a la ambientación.');
    }

    if (isset($_POST['track_save'], $_POST['track_id'])) {
        foreach ($cfg['tracks'] as $i=>$track) if (($track['id'] ?? '') === $_POST['track_id']) {
            $title = nexMusicAdminText($_POST['track_title'] ?? '',100); if ($title==='') throw new Exception('El título es obligatorio.');
            $cfg['tracks'][$i]['enabled'] = isset($_POST['track_enabled']);
            $cfg['tracks'][$i]['order'] = (int)($_POST['track_order'] ?? 100);
            $cfg['tracks'][$i]['realm'] = in_array($_POST['track_realm'] ?? '',array('both','legacy','seasonal'),true)?$_POST['track_realm']:'both';
            $cfg['tracks'][$i]['title'] = $title;
            $cfg['tracks'][$i]['artist'] = nexMusicAdminText($_POST['track_artist'] ?? '',80);
            $cfg['tracks'][$i]['url'] = nexMusicAdminUrl($_POST['track_url'] ?? '');
            $newFile = nexMusicAdminUpload('track_file', $track['id']); if ($newFile !== '') $cfg['tracks'][$i]['file'] = $newFile;
            nexMusicAdminSave($cfg); message('success','Pista actualizada.'); break;
        }
    }
    if (isset($_POST['track_delete'], $_POST['track_id'])) {
        foreach ($cfg['tracks'] as $i=>$track) if (($track['id'] ?? '') === $_POST['track_id']) {
            array_splice($cfg['tracks'],$i,1); nexMusicAdminSave($cfg); message('success','Pista retirada de la playlist.'); break;
        }
    }
    $cfg = nexMusicAdminLoad();
} catch (Throwable $ex) {
    message('error', 'Ambientación Nexora: ' . $ex->getMessage());
    $cfg = nexMusicAdminLoad();
}
$s = $cfg['settings'];
function nexMusicTrackFields($track, $creating=false) { ?>
    <div class="row"><div class="col-md-2 form-group"><label>Orden</label><input class="form-control" type="number" name="track_order" value="<?php echo nexMusicA($track['order'] ?? 100); ?>"></div><div class="col-md-3 form-group"><label>Reino</label><select class="form-control" name="track_realm"><?php foreach(array('both'=>'Legado + Seasonal','legacy'=>'Legado','seasonal'=>'Seasonal') as $v=>$l) echo '<option value="'.$v.'"'.(($track['realm'] ?? 'both')===$v?' selected':'').'>'.$l.'</option>'; ?></select></div><div class="col-md-4 form-group"><label>Título</label><input class="form-control" required name="track_title" value="<?php echo nexMusicA($track['title'] ?? ''); ?>"></div><div class="col-md-3 form-group"><label>Artista / colección</label><input class="form-control" name="track_artist" value="<?php echo nexMusicA($track['artist'] ?? ''); ?>"></div></div>
    <div class="row"><div class="col-md-6 form-group"><label>Archivo de audio <?php echo $creating?'':'(vacío conserva el actual)'; ?></label><input class="form-control" type="file" name="track_file" accept="audio/mpeg,audio/ogg,audio/webm,audio/mp4"></div><div class="col-md-6 form-group"><label>O URL HTTPS</label><input class="form-control" name="track_url" value="<?php echo nexMusicA($track['url'] ?? ''); ?>" placeholder="https://cdn.../pista.mp3"></div></div>
<?php } ?>
<h1 class="page-header">Ambientación Musical</h1>
<p class="lead">Una capa sonora reconocible para Nexora, controlada por el jugador y administrada desde un solo lugar.</p>
<div class="alert alert-info"><strong>Autoplay responsable:</strong> el navegador exige una interacción antes de reproducir con sonido. El jugador verá “Activar ambientación” y conservará el control de volumen, pausa y silencio.</div>
<div class="panel panel-default"><div class="panel-heading"><strong>Configuración del reproductor</strong></div><div class="panel-body"><form method="post">
    <label class="checkbox-inline"><input type="checkbox" name="enabled" <?php echo !empty($s['enabled'])?'checked':''; ?>> Reproductor activo</label>
    <label class="checkbox-inline"><input type="checkbox" name="shuffle" <?php echo !empty($s['shuffle'])?'checked':''; ?>> Orden aleatorio</label>
    <label class="checkbox-inline"><input type="checkbox" name="loop" <?php echo !isset($s['loop'])||$s['loop']?'checked':''; ?>> Repetición continua</label>
    <label class="checkbox-inline"><input type="checkbox" name="remember_state" <?php echo !isset($s['remember_state'])||$s['remember_state']?'checked':''; ?>> Recordar preferencias</label><hr>
    <div class="row"><div class="col-md-4 form-group"><label>Fuente principal</label><select class="form-control" name="source_mode"><?php foreach(array('local'=>'Archivos / URLs propios','youtube'=>'YouTube: mix o playlist','hybrid'=>'YouTube + respaldo local') as $v=>$l) echo '<option value="'.$v.'"'.(($s['source_mode'] ?? 'local')===$v?' selected':'').'>'.$l.'</option>'; ?></select></div><div class="col-md-8 form-group"><label>Enlace de YouTube</label><input class="form-control" name="youtube_url" value="<?php echo nexMusicA($s['youtube_url'] ?? ''); ?>" placeholder="https://www.youtube.com/watch?v=... o playlist?list=..."><p class="help-block">Admite un mix individual, un video o una playlist pública. No requiere API Key.</p></div></div>
    <div class="row"><div class="col-md-4 form-group"><label>Título</label><input class="form-control" name="player_title" value="<?php echo nexMusicA($s['title'] ?? 'Ambientación Nexora'); ?>"></div><div class="col-md-5 form-group"><label>Subtítulo</label><input class="form-control" name="player_subtitle" value="<?php echo nexMusicA($s['subtitle'] ?? 'Sonido del ecosistema'); ?>"></div><div class="col-md-3 form-group"><label>Volumen inicial (%)</label><input class="form-control" type="number" min="0" max="100" name="initial_volume" value="<?php echo nexMusicA($s['initial_volume'] ?? 35); ?>"></div></div>
    <button class="btn btn-primary" name="music_settings_save" value="1">Guardar configuración</button>
</form></div></div>
<h2>Playlist</h2>
<?php foreach ($cfg['tracks'] as $track) { ?><div class="panel panel-info"><div class="panel-heading"><strong><?php echo nexMusicA($track['title'] ?? 'Pista'); ?></strong> <span class="label label-default"><?php echo nexMusicA($track['realm'] ?? 'both'); ?></span></div><div class="panel-body"><form method="post" enctype="multipart/form-data"><input type="hidden" name="track_id" value="<?php echo nexMusicA($track['id']); ?>"><?php nexMusicTrackFields($track); ?><label class="checkbox-inline"><input type="checkbox" name="track_enabled" <?php echo !isset($track['enabled'])||$track['enabled']?'checked':''; ?>> Disponible</label><hr><button class="btn btn-primary" name="track_save" value="1">Guardar pista</button><button class="btn btn-danger pull-right" name="track_delete" value="1" onclick="return confirm('¿Retirar esta pista?');">Eliminar</button></form></div></div><?php } ?>
<div class="panel panel-success"><div class="panel-heading"><strong>Añadir pista</strong></div><div class="panel-body"><form method="post" enctype="multipart/form-data"><?php nexMusicTrackFields(array('order'=>100,'realm'=>'both'),true); ?><button class="btn btn-success" name="track_add" value="1">Añadir a la playlist</button></form></div></div>
