<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

ini_set('display_errors', 0);
error_reporting(E_ALL);

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$hasVersion = isset($_GET['v']) && trim((string)$_GET['v']) !== '';

function sendDefaultCover() {
    global $hasVersion;
    $defaultPath = __DIR__ . '/assets/img/default-cover.svg';
    while (ob_get_level()) {
        @ob_end_clean();
    }
    if (!headers_sent()) {
        header($hasVersion ? 'Cache-Control: public, max-age=86400' : 'Cache-Control: no-cache, must-revalidate, max-age=0');
        header('Content-Type: image/svg+xml');
        header('X-Content-Type-Options: nosniff');
    }
    if (is_file($defaultPath) && is_readable($defaultPath)) {
        $size = @filesize($defaultPath);
        if ($size !== false && !headers_sent()) header('Content-Length: ' . $size);
        @readfile($defaultPath);
    } else {
        $fallbackSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" fill="#1f1f1f"/><circle cx="50" cy="50" r="30" fill="#00CD3C"/></svg>';
        if (!headers_sent()) header('Content-Length: ' . strlen($fallbackSvg));
        echo $fallbackSvg;
    }
    exit;
}

function sendImageFile($path) {
    global $hasVersion;
    if (!is_file($path) || !is_readable($path)) {
        sendDefaultCover();
    }
    $size = @filesize($path);
    if ($size === false || $size <= 0) {
        sendDefaultCover();
    }
    $mime = function_exists('mime_content_type') ? @mime_content_type($path) : null;
    if (!$mime || strpos($mime, 'image/') !== 0) $mime = 'image/jpeg';
    if (!headers_sent()) {
        header($hasVersion ? 'Cache-Control: public, max-age=604800' : 'Cache-Control: no-cache, must-revalidate, max-age=0');
        header('Content-Type: ' . $mime);
        header('Content-Length: ' . $size);
        header('X-Content-Type-Options: nosniff');
    }
    while (ob_get_level()) {
        @ob_end_clean();
    }
    @readfile($path);
    exit;
}

if ($id <= 0) {
    sendDefaultCover();
}

try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("
        SELECT id, file_path, cover_cache_path, cover_hash, has_cover, cover_mime
        FROM songs
        WHERE id = :id AND is_missing = 0
    ");
    $stmt->execute([':id' => $id]);
    $song = $stmt->fetch();
    if (!$song) sendDefaultCover();

    $cacheDir = ensureCoverCacheDir();
    if (!empty($song['cover_cache_path'])) {
        $cached = __DIR__ . '/' . ltrim(str_replace('\\', '/', $song['cover_cache_path']), '/');
        if (is_file($cached) && isPathInside($cached, $cacheDir)) {
            sendImageFile($cached);
        }
    }

    $winFilePath = resolveFilesystemPath($song['file_path'], 'readable_file');
    if ($winFilePath === null) sendDefaultCover();

    $scanDirPath = resolveFilesystemPath(getScanPathSetting(), 'dir') ?? toWinPath(getScanPathSetting());
    $realFile = realpath($winFilePath) ?: $winFilePath;
    $realScanDir = $scanDirPath ? (realpath($scanDirPath) ?: $scanDirPath) : false;
    if (!$realFile || !$realScanDir || !isPathInside($realFile, $realScanDir)) {
        sendDefaultCover();
    }

    $cover = getEmbeddedCover($realFile);
    if (!$cover || empty($cover['data'])) {
        $update = $pdo->prepare("UPDATE songs SET has_cover = 0, cover_cache_path = NULL, cover_mime = NULL WHERE id = :id");
        $update->execute([':id' => $id]);
        sendDefaultCover();
    }

    $hash = md5($cover['data']);
    $extension = coverExtensionFromMime($cover['mime'] ?? 'image/jpeg');
    $cacheName = 'cover_' . $id . '_' . $hash . '.' . $extension;
    $cachePath = $cacheDir . '/' . $cacheName;
    $written = @file_put_contents($cachePath, $cover['data']);
    if ($written === false || $written <= 0 || !is_file($cachePath)) {
        sendDefaultCover();
    }
    $relativePath = 'storage/covers/' . $cacheName;

    $update = $pdo->prepare("
        UPDATE songs
        SET cover_hash = :cover_hash,
            has_cover = 1,
            cover_mime = :cover_mime,
            cover_cache_path = :cover_cache_path
        WHERE id = :id
    ");
    $update->execute([
        ':cover_hash' => $hash,
        ':cover_mime' => $cover['mime'] ?? 'image/jpeg',
        ':cover_cache_path' => $relativePath,
        ':id' => $id,
    ]);

    sendImageFile($cachePath);
} catch (Exception $e) {
    sendDefaultCover();
}
