<?php
$file = 'counter.dat';

// 读取并自增
$counter = (int)@file_get_contents($file);
$counter++;

// 使用 LOCK_EX 防止并发写入冲突
file_put_contents($file, $counter, LOCK_EX);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

// 辅助类 - HTTP请求和数据处理
class NetEaseHelper {
    /**
     * 执行CURL请求
     */
    public static function curl($url, $options = []) {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        
        // 默认User-Agent
        $ua = isset($options['ua']) ? $options['ua'] : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
        
        // POST数据
        if (!empty($options['post'])) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $options['post']);
        }
        
        // 自定义Headers
        if (!empty($options['Header'])) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $options['Header']);
        }
        
        // SSL验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }
    
    /**
     * 发送数据
     */
    public static function send($data, $type = 'json') {
        if ($type === 'json') {
            if (is_array($data)) {
                echo json_encode($data, JSON_UNESCAPED_UNICODE);
            } else {
                echo $data;
            }
        } else {
            echo $data;
        }
        exit;
    }
}

class Music_163_Rand {
    protected $info = [];
    protected $Array = [];
    protected $Msg;
    protected $id;
    protected $header = [
        'Host: music.163.com',
        'Origin: http://music.163.com',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Content-Type: application/x-www-form-urlencoded',
        'Referer: http://music.163.com/search/',
    ];
    
    public function __construct(Array $Array) {
        foreach ($Array as $k => $v) {
            $this->info[$k] = $v;
        }
        $this->ParameterException();
    }
    
    protected function ParameterException() {
        $id = $this->info['id'];
        if (!is_numeric($id)) {
            $this->Array = ['code' => -1, 'msg' => '请输入正确的歌单id'];
            $this->returns();
            return;
        }
        $this->getPlaylistSongs();
    }
    
    protected function getPlaylistSongs() {
        $id = $this->info['id'];
        $post_data = http_build_query(['s' => '100', 'id' => $id, 'n' => '100', 't' => '100']);
        $url = 'http://music.163.com/api/v6/playlist/detail';
        
        $data = NetEaseHelper::curl($url, [
            'post' => $post_data,
            'ua' => 'NeteaseMusic/8.6.31.211201171945(8006031);Dalvik/2.1.0 (Linux; U; Android 11; PCLM10 Build/RKQ1.200928.002)',
            'Header' => $this->header
        ]);
        
        $decoded = json_decode($data, true);
        
        if (empty($decoded['playlist']['trackIds'])) {
            $this->Array = ['code' => -1, 'msg' => '无法获取歌单信息'];
            $this->returns();
            return;
        }
        
        $array = $decoded['playlist']['trackIds'];
        $rand_song = $array[array_rand($array, 1)];
        $this->id = $rand_song['id'];
        
        $this->getSongDetail();
    }
    
    protected function getSongDetail() {
        $id = $this->id;
        $url = 'http://music.163.com/api/song/detail/?id=' . $id . '&ids=%5B' . $id . '%5D&csrf_token=';
        
        $data = json_decode(NetEaseHelper::curl($url), true);
        
        if (empty($data['songs'][0])) {
            $this->Array = ['code' => -1, 'msg' => '无法获取歌曲信息'];
            $this->returns();
            return;
        }
        
        $song = $data['songs'][0];
        $song_name = $song['name'] ?? '未知';
        $artist_name = $song['artists'][0]['name'] ?? '未知';
        $cover = $song['album']['picUrl'] ?? '';
        $music_url = 'http://music.163.com/song/media/outer/url?id=' . $id;
        $tail = $this->info['tail'] ?? '网易云音乐';
        
        $this->Array = [
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'id' => $id,
                'song' => $song_name,
                'singer' => $artist_name,
                'cover' => $cover,
                'music_url' => $music_url,
                'tail' => $tail
            ]
        ];
        
        $this->returns();
    }
    
    protected function returns() {
        $type = $this->info['type'] ?? 'json';
        
        switch ($type) {
            case 'text':
                if (isset($this->Array['data'])) {
                    $text = "歌曲：" . $this->Array['data']['song'] . "\n";
                    $text .= "歌手：" . $this->Array['data']['singer'];
                    echo $text;
                } else {
                    echo $this->Array['msg'];
                }
                break;
            case 'url':
                if (isset($this->Array['data']['music_url'])) {
                    header('Location: ' . $this->Array['data']['music_url']);
                } else {
                    echo json_encode($this->Array, JSON_UNESCAPED_UNICODE);
                }
                break;
            default:
                echo json_encode($this->Array, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                break;
        }
        exit;
    }
}

// 获取参数
$songId = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
$tail = isset($_REQUEST['tail']) ? $_REQUEST['tail'] : '网易云音乐';
$type = isset($_REQUEST['type']) ? $_REQUEST['type'] : 'json';

// 如果没提供歌单ID，使用默认热门歌单
if (empty($songId) || $songId <= 0) {
    $playlists = [71385702, 2884035, 3778678, 3779629, 19723756];
    $songId = $playlists[array_rand($playlists, 1)];
}

// 执行查询
new Music_163_Rand([
    'id' => $songId,
    'type' => $type,
    'tail' => $tail
]);
?>