<?php
/**
 * Alben: Anlegen, Auflisten, Löschen. Songs werden über musik.album_id zugeordnet.
 */
if (!defined('FUNCTIONS_ROOT')) {
    return;
}

/**
 * Alle Alben (sortiert nach Name). Toleriert fehlende Tabelle/Spalte icon_dateiname (Migration 010).
 * @return array<int, array{id: int, name: string, icon_dateiname: string|null, erstellt_am: string}>
 */
function function_alben_liste(): array {
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) return [];
    try {
        $stmt = $pdo->query("SELECT id, name, icon_dateiname, erstellt_am FROM alben ORDER BY name ASC");
        if ($stmt) return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        try {
            $stmt = $pdo->query("SELECT id, name, erstellt_am FROM alben ORDER BY name ASC");
            if (!$stmt) return [];
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rows as &$r) { $r['icon_dateiname'] = null; }
            return $rows;
        } catch (Throwable $e2) {
            return [];
        }
    }
    return [];
}

/**
 * Neues Album anlegen.
 */
function function_alben_erstellen(string $name): bool {
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) return false;
    $name = trim($name);
    if ($name === '') return false;
    $stmt = $pdo->prepare("INSERT INTO alben (name) VALUES (:name)");
    $stmt->execute(['name' => $name]);
    return $stmt->rowCount() > 0;
}

/**
 * Album aktualisieren (Name und/oder eigenes Icon).
 */
function function_alben_aktualisieren(int $id, ?string $name = null, ?string $icon_dateiname = null): bool {
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) return false;
    $updates = [];
    $params = ['id' => $id];
    if ($name !== null) {
        $updates[] = 'name = :name';
        $params['name'] = trim($name);
    }
    if ($icon_dateiname !== null) {
        $updates[] = 'icon_dateiname = :icon_dateiname';
        $params['icon_dateiname'] = $icon_dateiname === '' ? null : $icon_dateiname;
    }
    if (empty($updates)) return true;
    $stmt = $pdo->prepare("UPDATE alben SET " . implode(', ', $updates) . " WHERE id = :id");
    $stmt->execute($params);
    return $stmt->rowCount() >= 0;
}

/**
 * Ein zufälliges Song-Dateiname für eine Playlist (für Cover-Fallback).
 * @return string|null dateiname oder null wenn Playlist keine Songs hat
 */
function function_alben_random_song_dateiname(int $album_id): ?string {
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) return null;
    try {
        $stmt = $pdo->prepare("SELECT m.dateiname FROM musik m INNER JOIN playlist_tracks pt ON pt.musik_id = m.id WHERE pt.playlist_id = :aid ORDER BY RAND() LIMIT 1");
        $stmt->execute(['aid' => $album_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row && !empty($row['dateiname']) ? $row['dateiname'] : null;
    } catch (Throwable $e) {
        return null;
    }
}

/**
 * Playlist-IDs eines Songs (Many-to-Many über playlist_tracks).
 * @return int[]
 */
function function_alben_playlist_ids_fuer_musik(int $musik_id): array {
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) return [];
    try {
        $stmt = $pdo->prepare("SELECT playlist_id FROM playlist_tracks WHERE musik_id = :mid");
        $stmt->execute(['mid' => $musik_id]);
        $out = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            if (isset($row['playlist_id'])) $out[] = (int) $row['playlist_id'];
        }
        return $out;
    } catch (Throwable $e) {
        return [];
    }
}

/**
 * Song zu Playlists zuordnen (ersetzt bestehende Zuordnung).
 * @param int[] $playlist_ids
 */
function function_alben_playlists_setzen_fuer_musik(int $musik_id, array $playlist_ids): bool {
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) return false;
    try {
        $stmt = $pdo->prepare("DELETE FROM playlist_tracks WHERE musik_id = :mid");
        $stmt->execute(['mid' => $musik_id]);
        $ins = $pdo->prepare("INSERT IGNORE INTO playlist_tracks (playlist_id, musik_id) VALUES (:pid, :mid)");
        foreach ($playlist_ids as $pid) {
            if ((int) $pid > 0) {
                $ins->execute(['pid' => (int) $pid, 'mid' => $musik_id]);
            }
        }
        return true;
    } catch (Throwable $e) {
        return false;
    }
}

/**
 * Album löschen. Entfernt Zuordnung in playlist_tracks (CASCADE). Entfernt eigenes Icon aus storage.
 */
function function_alben_loeschen(int $id): bool {
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) return false;
    $icon = null;
    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'])) {
            $icon = $row['icon_dateiname'];
        }
    } catch (Throwable $e) {
        // Spalte icon_dateiname fehlt (Migration 010 nicht ausgeführt)
    }
    $stmt = $pdo->prepare("DELETE FROM alben WHERE id = :id");
    $stmt->execute(['id' => $id]);
    $ok = $stmt->rowCount() > 0;
    if ($ok && $icon && defined('STORAGE_ROOT')) {
        $path = rtrim(STORAGE_ROOT, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'album_icons' . DIRECTORY_SEPARATOR . $icon;
        if (is_file($path)) {
            @unlink($path);
        }
    }
    return $ok;
}
