<?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';
require FUNCTIONS_ROOT . '/functions_alben.php';

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

$audioDir = rtrim(STORAGE_ROOT, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'audio';
$albumIconsDir = rtrim(STORAGE_ROOT, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'album_icons';
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'] ?? '';

try {

if ($action === 'list') {
    $rows = function_musik_alle();
    if (empty($rows) && is_dir($audioDir)) {
        try {
            $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);
                }
            }
            $rows = function_musik_alle();
        } catch (Throwable $e) {
            /* Sync fehlgeschlagen (z. B. Migration 009 nicht ausgeführt), $rows bleibt leer */
        }
    }
    $files = [];
    foreach ($rows as $r) {
        $files[] = [
            'id'           => (int) $r['id'],
            'name'         => $r['dateiname'],
            'titel'        => $r['titel'] ?? null,
            'playlist_ids' => isset($r['playlist_ids']) && is_array($r['playlist_ids']) ? $r['playlist_ids'] : [],
            'playlists'    => isset($r['playlists']) && $r['playlists'] !== '' ? $r['playlists'] : 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) {
            $max = ini_get('upload_max_filesize');
            $post = ini_get('post_max_size');
            $err = 'Datei zu groß. Aktuelles Limit: ' . $max . ' (post_max_size: ' . $post . '). In .user.ini oder php.ini erhöhen (z.B. 512M).';
        } 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);
        $id = function_musik_einfuegen($name, $size, null);
        if ($id > 0) {
            $playlist_ids = [];
            $raw_pl = $_POST['playlist_ids'] ?? $_POST['playlist_ids[]'] ?? null;
            if (!empty($raw_pl) && is_array($raw_pl)) {
                $playlist_ids = array_filter(array_map('intval', $raw_pl));
            } elseif (isset($_POST['playlist_id']) && (int) $_POST['playlist_id'] > 0) {
                $playlist_ids = [(int) $_POST['playlist_id']];
            }
            if (!empty($playlist_ids)) {
                function_alben_playlists_setzen_fuer_musik($id, $playlist_ids);
            }
        }
        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;
    $playlist_ids = [];
    $raw_playlists = $_POST['playlist_ids'] ?? $_POST['playlist_ids[]'] ?? null;
    if (!empty($raw_playlists) && is_array($raw_playlists)) {
        $playlist_ids = array_filter(array_map('intval', $raw_playlists));
    }
    if ($titel !== null) {
        function_musik_aktualisieren($id, $titel);
    }
    if (!function_alben_playlists_setzen_fuer_musik($id, $playlist_ids)) {
        function_json_antwort(false, [], 'Playlist-Zuordnung fehlgeschlagen');
        exit;
    }
    function_json_antwort(true, ['message' => 'Aktualisiert']);
    exit;
}

if ($action === 'alben_list') {
    $alben = function_alben_liste();
    $list = array_map(function ($a) {
        return [
            'id' => (int) $a['id'],
            'name' => $a['name'],
            'icon' => !empty($a['icon_dateiname']) ? $a['icon_dateiname'] : null,
        ];
    }, $alben);
    function_json_antwort(true, ['alben' => $list]);
    exit;
}

if ($action === 'alben_create') {
    $name = isset($_POST['name']) ? trim((string) $_POST['name']) : '';
    if ($name === '') {
        function_json_antwort(false, [], 'Playlistname angeben');
        exit;
    }
    if (function_alben_erstellen($name)) {
        $alben = function_alben_liste();
        $neu = null;
        foreach ($alben as $a) {
            if ($a['name'] === $name) { $neu = ['id' => (int) $a['id'], 'name' => $a['name']]; break; }
        }
        function_json_antwort(true, ['album' => $neu]);
    } else {
        function_json_antwort(false, [], 'Playlist existiert bereits oder Fehler');
    }
    exit;
}

if ($action === 'alben_delete') {
    $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
    if ($id <= 0) {
        function_json_antwort(false, [], 'Ungültige ID');
        exit;
    }
    if (function_alben_loeschen($id)) {
        function_json_antwort(true, ['message' => 'Gelöscht']);
    } else {
        function_json_antwort(false, [], 'Löschen fehlgeschlagen');
    }
    exit;
}

if ($action === 'alben_update') {
    $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
    if ($id <= 0) {
        function_json_antwort(false, [], 'Ungültige ID');
        exit;
    }
    $name = isset($_POST['name']) ? trim((string) $_POST['name']) : null;
    if (!is_dir($albumIconsDir)) {
        @mkdir($albumIconsDir, 0755, true);
    }
    $icon_dateiname = null;
    if (!empty($_FILES['icon']) && $_FILES['icon']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['icon']['name'], PATHINFO_EXTENSION));
        $allowed = ['svg', 'png', 'jpg', 'jpeg', 'gif', 'webp'];
        if (!in_array($ext, $allowed, true)) {
            function_json_antwort(false, [], 'Nur Bilder (SVG, PNG, JPG, GIF, WebP) erlaubt');
            exit;
        }
        $icon_dateiname = $id . '.' . $ext;
        $path = $albumIconsDir . DIRECTORY_SEPARATOR . $icon_dateiname;
        if (!move_uploaded_file($_FILES['icon']['tmp_name'], $path)) {
            function_json_antwort(false, [], 'Icon speichern fehlgeschlagen');
            exit;
        }
    }
    $updates = [];
    $params = ['id' => $id];
    if ($name !== null) {
        $updates[] = 'name = :name';
        $params['name'] = $name;
    }
    if ($icon_dateiname !== null) {
        $updates[] = 'icon_dateiname = :icon_dateiname';
        $params['icon_dateiname'] = $icon_dateiname;
    }
    if (!empty($updates)) {
        $pdo = $GLOBALS['pdo'] ?? null;
        if ($pdo) {
            $stmt = $pdo->prepare("UPDATE alben SET " . implode(', ', $updates) . " WHERE id = :id");
            $stmt->execute($params);
        }
    }
    function_json_antwort(true, ['message' => 'Aktualisiert']);
    exit;
}

if ($action === 'alben_icon_remove') {
    $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
    if ($id <= 0) {
        function_json_antwort(false, [], 'Ungültige ID');
        exit;
    }
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) {
        function_json_antwort(false, [], 'Fehler');
        exit;
    }
    try {
        $stmt = $pdo->prepare("SELECT icon_dateiname FROM alben WHERE id = :id");
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row && !empty($row['icon_dateiname'])) {
            $path = $albumIconsDir . DIRECTORY_SEPARATOR . $row['icon_dateiname'];
            if (is_file($path)) {
                @unlink($path);
            }
        }
        $stmt = $pdo->prepare("UPDATE alben SET icon_dateiname = NULL WHERE id = :id");
        $stmt->execute(['id' => $id]);
    } catch (Throwable $e) {
        // Spalte icon_dateiname fehlt (Migration 010 nicht ausgeführt)
    }
    function_json_antwort(true, ['message' => 'Icon entfernt']);
    exit;
}

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

} catch (Throwable $e) {
    function_json_antwort(false, [], 'Serverfehler');
}
