<?php 
error_reporting(0);
$headers = Array(
	'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0',
	'Cookie: bid=U7wtK1mCeE8;_pk_id.100001.4cf6=6596e5bc44600f74.1764850398.;__yadk_uid=GjwfdJ2w4QBCmuvwWnOaaO8rz207S44Y;ll="118356";_vwo_uuid_v2=DF00386D0B256B136B0102AC27F915608|91b94475d0f6b69100980a95411c71ff;_ga=GA1.2.1659727348.1764850399;_ga_PRH9EWN86K=GS2.2.s1775195053$o1$g0$t1775195053$j60$l0$h0;push_noty_num=0;push_doumail_num=0;__utmc=30149280;__utmc=223695111;_pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1781870432%2C%22https%3A%2F%2Fwww.so.com%2Flink%3Fm%3Du5jnnuxhW408v8XTdKeOrerlHf4bZepaVPqcdIK%2BFtQXjbeqBrO16ypkbjq%2F35WtsJvUT1DPfE8NaI2zdF669TWGEdt2g%2BVcm1Sp2lm21utRDB4I%2BPAoYso4IMXk%3D%22%5D;_pk_ses.100001.4cf6=1;ap_v=0,6.0;dbcl2="223293173:qXJdjbyhilU";ck=hRzS;__utma=30149280.1659727348.1764850399.1781861579.1781870456.12;__utmb=30149280.0.10.1781870456;__utmz=30149280.1781870456.12.12.utmcsr=open.weixin.qq.com|utmccn=(referral)|utmcmd=referral|utmcct=/connect/qrconnect;__utma=223695111.1501386649.1764850399.1781861579.1781870456.10;__utmb=223695111.0.10.1781870456;__utmz=223695111.1781870456.10.9.utmcsr=open.weixin.qq.com|utmccn=(referral)|utmcmd=referral|utmcct=/connect/qrconnect;frodotk_db="78a1a45eb8e46eb569e4ed1c2aad4c1f"',
'Cache-Control:max-age=0',
'Accept-Language:zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'Upgrade-Insecure-Requests:1',
'Referer: https://movie.douban.com/'
);

if($_GET['img_url']){
	set_time_limit(0);
	header('Content-Type: image/webp');
	echo request($_GET['img_url'],'GET','',$headers);
	exit();
}else{
	Header('Content-Type: application/json');
}
$config = include('config.php');
$domain_list = $config['domain'];

$keyword = trim($_GET['keyword']);
$type = preg_match('/\d{7,}/', $keyword)?'id':'name';

if($type=='id'){
	$id = $keyword;
	get_content($id);
}else{
	$keyword = urlencode($keyword);
	$start = $_GET['start']??0;
	$url = "https://search.douban.com/movie/subject_search?search_text=$keyword&cat=1002".($start>0?'&start='.$start:'');
	$res = request($url,'GET','',$headers);
	preg_match_all('/window\.__DATA__\s=\s(\{.*?\});\s+window\.__USER__/is',$res,$list_matches);
	$list = json_decode(trim($list_matches[1][0]) ,true);
	$i=0;
	$list_html = '<ul style="list-style-type:none;height: 350px;">';
	foreach($list['items'] as $item){
		if($item['id']){
			$list_html .= '<li style="display:-webkit-inline-box;width:183.8px;padding:10px;"><a href="javascript:get_douban('.$item['id'].');"><img style="width:163.8px;height:203.7px;" src="douban_api.php?img_url='.urlencode($item['cover_url']).'" />'.$item['title'].'</a></li>';
			$i = $i + 1;
		}
	}
	$list_html .= '</ul>';
	echo json_encode(Array('code'=>1,'msg'=>'search','total'=>(int)$list['total'],'start'=>(int)$start,'data'=>$list_html));
}

function get_content($id){
    global $headers;
    $url = "https://movie.douban.com/subject/$id/?from=showing";    
    $res = request($url, 'GET', '', $headers);

    // 【调试】如果希望查看实际返回的页面，取消下面注释（仅调试用）
    // file_put_contents('debug_douban_' . $id . '.html', $res);
    
    // 基础信息提取
    preg_match('/<div\s+id="info"[^>]*>(.*?)<\/div>/is', $res, $info_matches);
    preg_match('/<div\s+id="mainpic"[^>]*>(.*?)<\/div>/is', $res, $mainpic_matches);
    preg_match('/<div\s+id="content"[^>]*>[\s\S]*?<h1>(.*?)<\/h1>[\s\S]*?<\/div>/is', $res, $title_matches);
    preg_match_all('/<span\s.*>(.*)<\/span>/', $title_matches[1] , $title_match);
    preg_match('/<div\s.+id="link\-report\-intra"[^>]*>\s*?(.*?)<\/div>/is', $res, $intro_matches);
    
    // ========== 评分提取（基于豆瓣实际页面结构） ==========
    $rate = '';
    // 方式1: 标准豆瓣评分 class="ll rating_num"
    if(preg_match('/<strong\s+class="ll\srating_num"[^>]*>([\d\.]+)<\/strong>/i', $res, $m)) {
        $rate = trim($m[1]);
    }
    // 方式2: property="v:average"
    if(!$rate && preg_match('/<strong[^>]*property="v:average"[^>]*>([\d\.]+)<\/strong>/i', $res, $m)) {
        $rate = trim($m[1]);
    }
    // 方式3: 任意包含 rating_num 的 strong
    if(!$rate && preg_match('/<strong[^>]*rating_num[^>]*>([\d\.]+)<\/strong>/i', $res, $m)) {
        $rate = trim($m[1]);
    }
    // 方式4: 从 JSON-LD 结构化数据中提取
    if(!$rate && preg_match('/"ratingValue":\s*"([\d\.]+)"/', $res, $m)) {
        $rate = trim($m[1]);
    }
    // 方式5: 直接从页面中寻找 "X.X分" 模式（兜底）
    if(!$rate && preg_match('/([\d\.]+)\s*分/', $res, $m)) {
        $rate = trim($m[1]);
    }
    if(!$rate){
        $rate = '暂无';
    }
    // ====================================================
    
    preg_match('/IMDb:<\/span>(.*?)<br>/i',$info_matches[1],$imdb_matches);
    preg_match('/<p class="comment-content">([\s\S]*?)<\/p>/', $res, $comment_matches);

    // 处理基础信息
    $title = $title_match[1][0].$title_match[1][1];
    $intro = trim(strip_tags(trim($intro_matches[1])));
    $hot_comment = isset($comment_matches[1]) ? trim($comment_matches[1]) : '暂无热评';
    
    // 处理主图
    preg_match_all('/<img\s+[^>]*?src=["\']([^"\']+)["\']/i', $mainpic_matches[1], $pic_matches);
    $image_url = $pic_matches[1][0] ?? '';
    $img_path = '';
    if($image_url){
        $img_tmp = request($image_url, 'GET', '', $headers);
        $img_path = 'upload/'.date('YmdHis').'_'.uniqid().'.jpg';
        file_put_contents($img_path, $img_tmp);
    }

    // 处理信息标签
    $info = preg_replace('/<span\sclass=[\'"]?pl[\'"]?>(.*?)<\/span>/i',"<strong>$1</strong>",$info_matches[1] ?? '');
    $info = preg_replace('/<a\shref=".*?".*?>(.*?)<\/a>/i',"$1",$info);
    $info = preg_replace('/<span\s.*?[\'"].*?[\'"]?>(.*?)<\/span>/i',"$1",$info);
    $info = str_replace(['<br/>',' '],['',''],$info);
    $lines = explode("\n", $info);
    $country = $type = $lang = '';
    foreach($lines as $i => $string){
        if(empty(trim($string)) || $i == count($lines)-1){
            unset($lines[$i]);
        }else{
            $text = trim($lines[$i]);
            if(strpos($text, '制片国家')>0) $country = str_replace('<strong>制片国家/地区:</strong>','',$text);
            if(strpos($text, '类型')>0) $type = str_replace('<strong>类型:</strong>','',$text);
            if(strpos($text, '语言')>0) $lang = str_replace('<strong>语言:</strong>','',$text);
            $lines[$i] = '<p>'.$text.'</p>';
        }
    }
    $title .= $country?' ['.$country.']':'';
    $title .= $type?' ['.$type.']':'';
    $title .= $lang?' '.$lang:' ';
    $title .= ($rate != '暂无') ? ' '.$rate.'分' : '';
    $info = implode("\n", $lines);

    if(!$title && !$intro){
        echo json_encode(Array('code'=>2,'msg'=>'操作频繁，请稍后再试~'));
        exit();
    }

   // 尝试1: 从主页面获取更多图片（剧照模块）
    $images = [];
    if(preg_match('/<div class="related-pic-video">([\s\S]*?)<\/div>/is', $res, $related_matches)){
        preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/i', $related_matches[1], $main_page_pics);
        if(!empty($main_page_pics[1])){
            $images = array_slice($main_page_pics[1], 0, 2);
        }
    }

    // 尝试2: 如果主页面没有，再访问剧照页面
    if(empty($images)){
        $photos_url = "https://movie.douban.com/subject/{$id}/photos?type=S";
        $photos_res = request($photos_url, 'GET', '', $headers);
        if(preg_match_all('/<img[^>]+src=["\']([^"\']+doubanio\.com[^"\']+)["\']/i', $photos_res, $photo_matches)){
            $unique_photos = array_unique($photo_matches[1]);
            $filtered = [];
            foreach($unique_photos as $pic){
                if(strpos($pic, 's_') === false || strpos($pic, 'ratio') !== false){
                    $filtered[] = $pic;
                }
            }
            $images = array_slice($filtered, 0, 2);
        }
    }

    // 处理图片下载和HTML生成
    $movie_images_html = '';
    if(!empty($images)){
        $movie_images_html = '<div class="movie-images" style="margin: 15px 0;"><h3>电影剧照：</h3><div style="display: flex; gap: 10px; flex-wrap: wrap;">';
        foreach($images as $img){
            $clean_img_url = preg_replace('/\/s\d+x\d+\//', '/', $img);
            $img_content = request($clean_img_url, 'GET', '', $headers);
            if($img_content && strlen($img_content) > 1000){
                $max_size = 524288;
                $img_filename = 'upload/'.date('YmdHis').'_'.uniqid().'.jpg';
                $original_size = strlen($img_content);
                if($original_size > $max_size) {
                    $temp_file = tempnam(sys_get_temp_dir(), 'img');
                    file_put_contents($temp_file, $img_content);
                    $image_info = getimagesize($temp_file);
                    $mime_type = $image_info['mime'];
                    switch($mime_type) {
                        case 'image/jpeg':
                            $image = imagecreatefromjpeg($temp_file);
                            break;
                        case 'image/png':
                            $image = imagecreatefrompng($temp_file);
                            break;
                        case 'image/gif':
                            $image = imagecreatefromgif($temp_file);
                            break;
                        case 'image/webp':
                            $image = imagecreatefromwebp($temp_file);
                            break;
                        default:
                            file_put_contents($img_filename, $img_content);
                            unlink($temp_file);
                            continue 2;
                    }
                    $quality = 70;
                    do {
                        ob_start();
                        imagejpeg($image, null, $quality);
                        $compressed_data = ob_get_clean();
                        $compressed_size = strlen($compressed_data);
                        if($compressed_size > $max_size) {
                            $quality -= 5;
                        } else {
                            break;
                        }
                    } while ($quality > 8);
                    file_put_contents($img_filename, $compressed_data);
                    imagedestroy($image);
                    unlink($temp_file);
                } else {
                    file_put_contents($img_filename, $img_content);
                }
                $movie_images_html .= '<div style="flex: 1; min-width: 200px;"><img src="'.$img_filename.'" style="width: 100%; height: auto; border-radius: 4px;" alt="电影剧照"></div>';
            }
        }
        $movie_images_html .= '</div></div>';
    } else {
        $movie_images_html = '<div style="margin:15px 0;padding:10px;background:#f5f5f5;"><p>暂未获取到相关剧照</p></div>';
    }

    $content = '<div class="card"><div class="movie-info"><img src="'.$img_path.'" alt="'.$title_match[1][0].'" /><div class="movie-info-content"><span class="movie-title">'.$title_match[1][0].'<span class="badge-vlo1">'.$rate.'分</span></span>'.$info.'<p><strong>豆瓣ID：</strong><a href="https://movie.douban.com/subject/'.$id.'/" target="_blank" rel="noopener">'.$id.'</a>&nbsp; &nbsp;<strong>IMDb：</strong><a href="https://www.imdb.com/title/'.trim($imdb_matches[1]).'/" target="_blank" rel="noopener">'.trim($imdb_matches[1]).'</a></p></div></div></div><h3>影视简介</h3><div>'.$intro.'</div><h3>影视热评</h3><div>'.$hot_comment.'</div><h3>下载地址：</h3>'.$movie_images_html;
    echo json_encode(Array('code'=>0,'msg'=>'ok','title'=>$title??'','data'=>$content));
}

// 增强版 request 函数
function request($url, $method = "GET", $data = [], $headers = []) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_ENCODING, '');       // 自动处理 gzip/deflate
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 跟随重定向
    if ($method == 'POST' && !empty($data)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}