<?php
/**
 * Album-Cover: Eigenes Icon oder zufälliges Song-Cover aus dem Album.
 * Aufruf: /album_cover.php?album_id=123
 */
require __DIR__ . '/../config.php';
require FUNCTIONS_ROOT . '/functions_alben.php';

$album_id = isset($_GET['album_id']) ? (int) $_GET['album_id'] : 0;
if ($album_id <= 0) {
    http_response_code(400);
    exit;
}

$pdo = $GLOBALS['pdo'] ?? null;
if (!$pdo) {
    http_response_code(500);
    exit;
}

// Album existiert?
$check = $pdo->prepare("SELECT id FROM alben WHERE id = :id");
$check->execute(['id' => $album_id]);
if (!$check->fetch()) {
    http_response_code(404);
    exit;
}

$custom = '';
try {
    $stmt = $pdo->prepare("SELECT icon_dateiname FROM alben WHERE id = :id");
    $stmt->execute(['id' => $album_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $custom = $row['icon_dateiname'] ?? '';
} catch (Throwable $e) {
    // Spalte icon_dateiname fehlt (Migration 010 nicht ausgeführt)
}

$iconsDir = rtrim(STORAGE_ROOT, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'album_icons';
if ($custom !== '' && is_file($iconsDir . DIRECTORY_SEPARATOR . $custom)) {
    $path = $iconsDir . DIRECTORY_SEPARATOR . $custom;
    $ext = strtolower(pathinfo($custom, PATHINFO_EXTENSION));
    $mimes = ['svg' => 'image/svg+xml', 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'webp' => 'image/webp'];
    $mime = $mimes[$ext] ?? 'application/octet-stream';
    header('Content-Type: ' . $mime);
    header('Cache-Control: public, max-age=86400');
    header('Content-Length: ' . filesize($path));
    readfile($path);
    exit;
}

$dateiname = function_alben_random_song_dateiname($album_id);
if ($dateiname !== null) {
    header('Location: /audio_cover.php?f=' . rawurlencode($dateiname), true, 302);
    exit;
}

http_response_code(404);
