<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/static/php/autoload.php';

use Meting\Meting;

function ensureCacheDir($dir) {
    if (!is_dir($dir)) {
        @mkdir($dir, 0777, true);
        @chmod($dir, 0777);
    }
    return is_dir($dir) && is_writable($dir);
}

$songId = $_GET['id'] ?? '';

$pageTitle = '';
$pageKeywords = '';
$pageDescription = '';

function getVipCookieFromApi() {
    $apiUrl = 'https://puduoduo.top/cookie.php?action=getCookie';
    
    try {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200 || empty($response)) {
            error_log("获取VIP Cookie失败: HTTP {$httpCode}");
            return null;
        }
        
        $data = json_decode($response, true);
        
        if (!isset($data['code']) || $data['code'] !== 200) {
            error_log("获取VIP Cookie失败: API返回错误 " . json_encode($data));
            return null;
        }
        
        $cookieParts = [];
        foreach ($data['data'] as $key => $value) {
            if (!empty($value)) {
                $cookieParts[] = $key . '=' . $value;
            }
        }
        
        return implode('; ', $cookieParts);
        
    } catch (Exception $e) {
        error_log("获取VIP Cookie异常: " . $e->getMessage());
        return null;
    }
}

function encryptPicId($id) {
    $magic = str_split('3go8&$8*3*3h0k(2)2');
    $song_id = str_split((string)$id);

    for ($i = 0; $i < count($song_id); $i++) {
        $song_id[$i] = chr(ord($song_id[$i]) ^ ord($magic[$i % count($magic)]));
    }

    $result = base64_encode(md5(implode('', $song_id), true));
    $result = str_replace('/', '_', $result);
    $result = str_replace('+', '-', $result);

    return $result;
}

function getPicUrl($picId, $size = 300) {
    if (empty($picId)) {
        return 'https://picsum.photos/seed/default/' . $size . '/' . $size;
    }
    
    $encryptedId = encryptPicId($picId);
    return 'https://p3.music.126.net/' . $encryptedId . '/' . $picId . '.jpg?param=' . $size . 'y' . $size;
}

function fetchSongData($songId) {
    try {
        $meting = new Meting('netease');
        $meting->format(true);
        
        $result = $meting->song($songId);
        $songs = json_decode($result, true);
        
        if (is_array($songs) && !empty($songs)) {
            foreach ($songs as &$song) {
                $currentSongId = $song['id'];
                $song['songId'] = $currentSongId;
                $song['id'] = 'https://music.163.com/#/song?id=' . $currentSongId;
                
                $picResult = $meting->pic($song['pic_id'], 300);
                $picData = json_decode($picResult, true);
                $song['pic_id'] = $picData['url'] ?? '';
                
                $lyricResult = $meting->lyric($song['lyric_id']);
                $lyricData = json_decode($lyricResult, true);
                $song['lyric_id'] = $lyricData['lyric'] ?? '';
            }
            return $songs;
        }
    } catch (Exception $e) {
        error_log('获取歌曲数据失败: ' . $e->getMessage());
    }
    
    return [];
}

$songData = [];
if (!empty($songId)) {
    $cacheDir = __DIR__ . '/static/cache/player';
    $canWriteCache = PLAYER_CACHE_ENABLED && ensureCacheDir($cacheDir);
    
    $cacheFile = $cacheDir . '/' . $songId . '.json';
    $lockFile = $cacheDir . '/' . $songId . '.lock';

    if ($canWriteCache && file_exists($cacheFile)) {
        $songData = json_decode(file_get_contents($cacheFile), true) ?: [];
    }

    if (empty($songData)) {
        if ($canWriteCache) {
            $lockHandle = @fopen($lockFile, 'c');
            
            if ($lockHandle === false) {
                $songData = fetchSongData($songId);
            } elseif (flock($lockHandle, LOCK_EX)) {
                if (file_exists($cacheFile)) {
                    $songData = json_decode(file_get_contents($cacheFile), true) ?: [];
                }
                
                if (empty($songData)) {
                    $songData = fetchSongData($songId);
                    
                    if (!empty($songData)) {
                        @file_put_contents($cacheFile, json_encode($songData, JSON_UNESCAPED_UNICODE));
                    }
                }
                
                flock($lockHandle, LOCK_UN);
                fclose($lockHandle);
                @unlink($lockFile);
            } else {
                fclose($lockHandle);
                usleep(100000);
                
                if (file_exists($cacheFile)) {
                    $songData = json_decode(file_get_contents($cacheFile), true) ?: [];
                }
                
                if (empty($songData)) {
                    $songData = fetchSongData($songId);
                }
            }
        } else {
            $songData = fetchSongData($songId);
        }
    }
}

$song = !empty($songData) && is_array($songData) ? $songData[0] : null;

if ($song) {
    $songName = $song['name'] ?? '';
    $artistName = is_array($song['artist']) ? implode(', ', $song['artist']) : $song['artist'];
    
    $pageTitle = $songName . ' - ' . $artistName . ' - ' . $siteConfig['name'];
    $pageKeywords = $songName . ',' . $artistName . ',MP3,下载,在线播放,免费';
    $pageDescription = $siteConfig['name'] . '收听' . $songName . '，演唱者：' . $artistName . '，支持免费下载和在线播放';
}

function fetchRelatedSongs($cleanSongName) {
    try {
        $meting = new Meting('netease');
        $meting->format(true);
        
        $result = $meting->search($cleanSongName, [
            'page' => 1,
            'limit' => 30
        ]);
        
        return json_decode($result, true) ?: [];
    } catch (Exception $e) {
        error_log('获取相关歌曲失败: ' . $e->getMessage());
        return [];
    }
}

function searchRelatedSongs($cleanSongName) {
    $cacheDir = __DIR__ . '/static/cache/related';
    $canWriteCache = RELATED_CACHE_ENABLED && ensureCacheDir($cacheDir);
    
    $cacheFile = $cacheDir . '/' . md5($cleanSongName) . '.json';
    $lockFile = $cacheDir . '/' . md5($cleanSongName) . '.lock';

    if ($canWriteCache && file_exists($cacheFile)) {
        return json_decode(file_get_contents($cacheFile), true) ?: [];
    }

    if ($canWriteCache) {
        $lockHandle = @fopen($lockFile, 'c');
        if ($lockHandle === false) {
            return fetchRelatedSongs($cleanSongName);
        }
        
        if (flock($lockHandle, LOCK_EX)) {
            if (file_exists($cacheFile)) {
                flock($lockHandle, LOCK_UN);
                fclose($lockHandle);
                @unlink($lockFile);
                return json_decode(file_get_contents($cacheFile), true) ?: [];
            }

            $searchResults = fetchRelatedSongs($cleanSongName);
            
            if ($searchResults && is_array($searchResults) && !empty($searchResults)) {
                @file_put_contents($cacheFile, json_encode($searchResults, JSON_UNESCAPED_UNICODE));
            }
            
            flock($lockHandle, LOCK_UN);
            fclose($lockHandle);
            @unlink($lockFile);
            return $searchResults;
        } else {
            fclose($lockHandle);
            usleep(100000);
            if (file_exists($cacheFile)) {
                return json_decode(file_get_contents($cacheFile), true) ?: [];
            }
            return fetchRelatedSongs($cleanSongName);
        }
    } else {
        return fetchRelatedSongs($cleanSongName);
    }
}

function parseSongNameKeywords($songName) {
    $cleanName = preg_replace('/\(.*\)|（.*）/', '', $songName);
    
    $keywords = preg_split('/[\s\-—–_、，,；;；]+/u', $cleanName);
    
    $keywords = array_filter($keywords, function($keyword) {
        return !empty(trim($keyword));
    });
    
    return array_values($keywords);
}

$relatedSongs = [];
if (!empty($song)) {
    $artistName = is_array($song['artist']) ? $song['artist'][0] : $song['artist'];
    $songName = $song['name'] ?? '';
    
    if (!empty($artistName) && !empty($songName)) {
        $pageTitle = $songName . ' - ' . $artistName . ' - MP3在线播放与免费下载 - ' . $siteConfig['name'] . 'MP3音乐下载';
        
        $pageKeywords = $artistName . '-' . $songName . 'mp3下载,' . $artistName . '-' . $songName . '歌曲网盘下载,' . $songName . '免费下载,' . $songName . 'lrc歌词下载,' . $artistName . '的' . $songName . ',' . $songName . '歌词下载';
        $pageDescription = $artistName . '的' . $songName . '免费下载,提供' . $songName . '的mp3下载,' . $songName . '网盘下载，' . $songName . 'lrc歌词下载，' . $artistName . '的' . $songName . '在线播放';
        
        $keywords = parseSongNameKeywords($songName);
        $searchResults = [];
        $searchedIds = [];
        
        foreach ($keywords as $keyword) {
            $results = searchRelatedSongs($keyword);
            
            foreach ($results as $result) {
                if (!in_array($result['id'], $searchedIds)) {
                    $searchResults[] = $result;
                    $searchedIds[] = $result['id'];
                }
            }
        
        if (count($searchResults) >= 30) {
            break;
        }
    }
    
    if (!empty($searchResults)) {
        $relatedSongs = $searchResults;
    }
}
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo htmlspecialchars($pageTitle); ?></title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta name="author" content="<?php echo htmlspecialchars($siteConfig['name']); ?>">
<link rel="canonical" href="<?php echo $siteUrl . str_replace('{id}', $songId, '/player/{id}.html'); ?>">
<meta name="keywords" content="<?php echo htmlspecialchars($pageKeywords); ?>">
<meta name="description" content="<?php echo htmlspecialchars($pageDescription); ?>">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="<?php echo htmlspecialchars($siteConfig['name']); ?>">
<meta name="application-name" content="<?php echo htmlspecialchars($siteConfig['name']); ?>">
<meta name="format-detection" content="telephone=no">
<link rel="shortcut icon" href="<?php echo htmlspecialchars($siteConfig['favicon']); ?>">
<link rel="apple-touch-icon" href="/static/img/apple.png?v=20260521">
<link rel="stylesheet" href="/static/css/amazeui.min.css?v=20260521">
<link rel="stylesheet" href="/static/css/APlayer.min.css?v=20260521">
<link rel="stylesheet" href="/static/css/style.css?v=20260521">
<script src="/static/js/jquery.min.js?v=20260521"></script>
</head>
<body class="page-player">
    <header id="header" class="glass-card">
        <div class="header-content">
            <h1 id="site-title-layout">
                <a class="title site-title" href="/" style="color: <?php echo htmlspecialchars($siteConfig['color']); ?>"><?php echo htmlspecialchars($siteConfig['name']); ?></a>
            </h1>
            <nav class="nav">
                <ul>
                    <li><a href="/">首页</a></li>
                    <li><a href="/playlist.html">歌单</a></li>
                </ul>
            </nav>
        </div>
    </header>
    <section class="am-g about">
        <div class="am-container am-margin-vertical-xl">
            <div class="am-u-lg-12 am-padding-vertical">
                <form id="j-search-form" class="am-form am-margin-bottom-lg" method="get" action="/" onsubmit="return submitSearch(event)">
                    <div class="am-u-md-12 am-u-sm-centered">
                        <div class="am-form-group">
                            <input id="j-search-input" type="text" class="am-form-field am-input-lg am-text-center am-radius" placeholder="请输入歌名" pattern="^.+$" required title="请输入搜索关键词" oninvalid="this.setCustomValidity('请输入搜索关键词');" oninput="this.setCustomValidity('');" style="border-color: RGB: 40, 40, 40">
                        </div>

                        <button type="submit" class="am-btn am-btn-primary am-btn-lg am-btn-block am-radius" style="background-color: <?php echo htmlspecialchars($siteConfig['color']); ?> !important;">音乐搜索</button>
                    </div>
                </form>
            </div>
            <hr style="margin: 15px 0;">
            <div class="am-u-lg-12 am-padding-vertical" style="padding-top: 0;">

                                <form id="j-main" class="am-form am-u-md-12 am-u-sm-centered music-main" style="display: block;">
                    <div class="am-g am-margin-bottom-sm">
                        <div class="am-u-lg-6">
                            <div class="am-input-group am-input-group-sm am-margin-bottom-sm">
                                <span class="am-input-group-label"></span>
                                <input id="j-src" class="am-form-field" readonly value="歌曲下载已经准备好，点击下载按钮" style="color: #999; user-select: none;">
                                <span class="am-input-group-btn">
                                    <a id="j-src-btn" class="am-btn am-btn-default" href="#">
                                         下载歌曲
                                    </a>
                                </span>
                            </div>
                        </div>
                        <div class="am-u-lg-6">
                            <div class="am-input-group am-input-group-sm am-margin-bottom-sm">
                                <span class="am-input-group-label"></span>
                                <input id="j-lrc" class="am-form-field" readonly>
                                <span class="am-input-group-btn">
                                    <a id="j-view-lyric-btn" class="am-btn am-btn-default">
                                         查看歌词
                                    </a>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div id="j-show" style="margin-top: -15px; margin-bottom: 15px;">
                        <div id="j-player" class="aplayer"></div>
                    </div>
                </form>
                <div class="am-u-md-12 am-u-sm-centered">
                    <div class="song-grid">
                    <?php if (!empty($relatedSongs) && is_array($relatedSongs)): ?>
                        <?php 
                        foreach (array_slice($relatedSongs, 0, 72) as $relatedSong): 
                            $songUrl = str_replace('{id}', $relatedSong['id'], '/player/{id}.html');
                    ?>
                            <a href="<?php echo htmlspecialchars($songUrl); ?>" class="song-card">
                                <img class="song-cover" src="<?php echo htmlspecialchars(getPicUrl($relatedSong['pic_id'] ?? '', 300), ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo htmlspecialchars($relatedSong['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                                <div class="song-info">
                                    <div class="song-title"><?php echo htmlspecialchars($relatedSong['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></div>
                                    <div class="song-artist"><?php echo htmlspecialchars(is_array($relatedSong['artist']) ? implode(', ', $relatedSong['artist']) : $relatedSong['artist'], ENT_QUOTES, 'UTF-8'); ?></div>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p style="text-align: center; color: #999; grid-column: 1 / -1;">暂无相关歌曲</p>
                    <?php endif; ?>
                </div>
                </div>
        </div>
        <!-- 下载歌曲弹窗 -->
        <div id="download-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; justify-content: center; align-items: center;">
            <div style="background: #fff; padding: 20px; border-radius: 8px; width: 90%; max-width: 500px; max-height: 80vh; overflow-y: auto; box-shadow: 0 4px 20px rgba(0,0,0,0.2);">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 style="margin: 0; font-size: 18px;">资源来源于第三方网盘</h3>
                    <span onclick="closeDownloadModal()" style="cursor: pointer; font-size: 24px; color: #999;">&times;</span>
                </div>
                <div id="download-list">
                    <p style="color: #999; text-align: center;">加载中...</p>
                </div>
            </div>
        </div>
    </section>
    <script src="/static/js/APlayer.min.js?v=20260521"></script>
    <script src="/static/js/main.js?v=20260521"></script>
    <script src="/static/js/amazeui.min.js?v=20260521"></script>
    <script src="/static/js/player.js?v=20260521"></script>
    <script>
        <?php if ($song && !empty($song['songId'])): ?>
        const songData = {
            name: '<?php echo addslashes($song['name'] ?? ''); ?>',
            artist: '<?php echo addslashes(is_array($song['artist']) ? implode(', ', $song['artist']) : $song['artist']); ?>',
            songId: '<?php echo $song['songId']; ?>',
            pic_id: '<?php echo $song['pic_id'] ?? ''; ?>',
            lyric: <?php echo json_encode($song['lyric_id'] ?? ''); ?>,
            themeColor: '<?php echo htmlspecialchars($siteConfig['color']); ?>'
        };
        initPlayer(songData);
        
        // 查看歌词按钮
        const viewLyricBtn = document.getElementById('j-view-lyric-btn');
        if (viewLyricBtn) {
            viewLyricBtn.href = '/lyrics/' + songData.songId + '.html';
        }
        <?php endif; ?>
    </script>
    <footer class="footer">
        <p class="am-text-sm">v3.6.5 @2026 <a href="/" target="_blank"><?php echo htmlspecialchars($siteConfig['name']); ?></a> <a href="/sitemap.xml" target="_blank">网站地图</a> 声明：本网站不存储任何音频数据，站内歌曲来自搜索引擎，如有侵犯版权请及时联系我们，我们将在第一时间处理！</p>
    </footer>
<script charset="UTF-8" id="LA_COLLECT" src="//sdk.51.la/js-sdk-pro.min.js"></script>
<script>LA.init({id:"LCXTdsIn64n1LcLD",ck:"LCXTdsIn64n1LcLD",screenRecord:true})</script>
</body>
</html>