<?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;

function sendDefaultCover() {
    $defaultPath = __DIR__ . '/assets/img/default-cover.svg';
    header('Cache-Control: public, max-age=86400');
    header('Content-Type: image/svg+xml');
    if (file_exists($defaultPath)) {
        header('Content-Length: ' . filesize($defaultPath));
        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>';
        header('Content-Length: ' . strlen($fallbackSvg));
        echo $fallbackSvg;
    }
    exit;
}

function sendImageFile($path) {
    $mime = function_exists('mime_content_type') ? mime_content_type($path) : null;
    if (!$mime || strpos($mime, 'image/') !== 0) $mime = 'image/jpeg';
    header('Cache-Control: public, max-age=604800');
    header('Content-Type: ' . $mime);
    header('Content-Length: ' . filesize($path));
    if (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 = toWinPath($song['file_path']);
    if (!file_exists($winFilePath)) sendDefaultCover();

    $realFile = realpath($winFilePath);
    $realScanDir = realpath(toWinPath(getScanPathSetting()));
    if (!$realFile || !$realScanDir || strpos(strtolower($realFile), strtolower($realScanDir)) !== 0) {
        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;
    file_put_contents($cachePath, $cover['data']);
    $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();
}
