<?php
/**
 * API für Meine Musik: Liste, Upload, Löschen. Songs in DB (Tabelle musik) + Dateien in storage/audio/
 */
require __DIR__ . '/../config.php';
require FUNCTIONS_ROOT . '/functions_db.php';
require FUNCTIONS_ROOT . '/functions_common.php';
require FUNCTIONS_ROOT . '/functions_musik.php';

header('Content-Type: application/json; charset=utf-8');

$audioDir = rtrim(STORAGE_ROOT, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'audio';
if (!is_dir($audioDir)) {
    @mkdir($audioDir, 0755, true);
}

function musik_safe_filename(string $name): string {
    $name = basename($name);
    $name = preg_replace('/[^a-zA-Z0-9_.-]/', '_', $name);
    return $name === '' ? 'audio' : $name;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'list') {
    $rows = function_musik_alle();
    if (empty($rows) && is_dir($audioDir)) {
        $exts = ['mp3', 'wav', 'ogg', 'm4a', 'aac'];
        foreach (scandir($audioDir) as $f) {
            if ($f === '.' || $f === '..') continue;
            $path = $audioDir . DIRECTORY_SEPARATOR . $f;
            if (!is_file($path)) continue;
            $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
            if (in_array($ext, $exts, true)) {
                function_musik_einfuegen($f, (int) filesize($path), null, null);
            }
        }
        $rows = function_musik_alle();
    }
    $files = [];
    foreach ($rows as $r) {
        $files[] = [
            'id'    => (int) $r['id'],
            'name'  => $r['dateiname'],
            'titel' => $r['titel'] ?? null,
            'album' => isset($r['album']) && $r['album'] !== '' ? $r['album'] : null,
            'size'  => (int) $r['groesse'],
            'url'   => '/audio_file.php?f=' . rawurlencode($r['dateiname']),
        ];
    }
    function_json_antwort(true, ['files' => $files]);
    exit;
}

if ($action === 'delete') {
    $name = trim($_POST['name'] ?? $_GET['name'] ?? '');
    $name = musik_safe_filename($name);
    if ($name === 'audio' && strpos($_POST['name'] ?? '', '.') === false) {
        function_json_antwort(false, [], 'Ungültiger Dateiname');
        exit;
    }
    $path = $audioDir . DIRECTORY_SEPARATOR . $name;
    function_musik_loeschen_nach_dateiname($name);
    if (is_file($path)) {
        @unlink($path);
    }
    function_json_antwort(true, ['message' => 'Gelöscht']);
    exit;
}

if ($action === 'upload') {
    if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        $err = $_FILES['file']['error'] ?? 'Keine Datei';
        if ($err === UPLOAD_ERR_INI_SIZE || $err === UPLOAD_ERR_FORM_SIZE) $err = 'Datei zu groß';
        elseif ($err === UPLOAD_ERR_NO_FILE) $err = 'Keine Datei gewählt';
        else $err = 'Upload-Fehler';
        function_json_antwort(false, [], $err);
        exit;
    }
    $orig = $_FILES['file']['name'];
    $name = musik_safe_filename($orig);
    $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
    if (!in_array($ext, ['mp3', 'wav', 'ogg', 'm4a', 'aac'], true)) $ext = 'mp3';
    if ($name === 'audio' || $name === '') {
        $name = 'audio_' . date('YmdHis') . '.' . $ext;
    } elseif (pathinfo($name, PATHINFO_EXTENSION) === '') {
        $name .= '.' . $ext;
    }
    $path = $audioDir . DIRECTORY_SEPARATOR . $name;
    if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
        $size = filesize($path);
        $album = isset($_POST['album']) ? trim((string) $_POST['album']) : null;
        $album = $album === '' ? null : $album;
        function_musik_einfuegen($name, $size, null, $album);
        function_json_antwort(true, [
            'name' => $name,
            'size' => $size,
            'url'  => '/audio_file.php?f=' . rawurlencode($name),
        ]);
    } else {
        function_json_antwort(false, [], 'Speichern fehlgeschlagen');
    }
    exit;
}

if ($action === 'update') {
    $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
    if ($id <= 0) {
        function_json_antwort(false, [], 'Ungültige ID');
        exit;
    }
    $titel = isset($_POST['titel']) ? trim((string) $_POST['titel']) : null;
    $album = isset($_POST['album']) ? trim((string) $_POST['album']) : null;
    if ($titel === null && $album === null) {
        function_json_antwort(false, [], 'Titel oder Album angeben');
        exit;
    }
    if (function_musik_aktualisieren($id, $titel, $album)) {
        function_json_antwort(true, ['message' => 'Aktualisiert']);
    } else {
        function_json_antwort(false, [], 'Aktualisierung fehlgeschlagen');
    }
    exit;
}

function_json_antwort(false, [], 'Unbekannte Aktion');
