<?php
/**
 * Sonora — search.php v5
 * Busca vídeos com capas reais. Cascata: Invidious → Piped → Scrape HTML
 */
session_name('sonora_sess');
session_start();
header('Content-Type: application/json; charset=utf-8');

if (empty($_SESSION['role'])) { http_response_code(401); echo json_encode(['success'=>false,'error'=>'Faça login']); exit; }

$q     = trim($_GET['q'] ?? '');
$limit = min((int)($_GET['limit'] ?? 16), 24);
if (!$q) { echo json_encode(['success'=>false,'error'=>'Query vazia']); exit; }

function do_curl($url, $to=9) {
    if (!function_exists('curl_init')) return false;
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL=>$url, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>$to,
        CURLOPT_FOLLOWLOCATION=>true, CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36',
        CURLOPT_HTTPHEADER=>['Accept-Language: pt-BR,pt;q=0.9,en;q=0.8'],
    ]);
    $b = curl_exec($ch); $c = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
    return ($c >= 200 && $c < 300 && $b) ? $b : false;
}

function safe_thumb($id, $thumbnails=[]) {
    // Sempre retorna URL direta do ytimg (não passa pelo Invidious)
    if (!empty($thumbnails)) {
        foreach ($thumbnails as $t) {
            $u = $t['url'] ?? '';
            if (strpos($u, 'ytimg.com') !== false) return $u;
        }
    }
    return "https://i.ytimg.com/vi/{$id}/hqdefault.jpg";
}

function fmt_dur($s) {
    $s = max(0,(int)$s);
    return floor($s/60).':'.str_pad($s%60,2,'0',STR_PAD_LEFT);
}

// ── 1. Invidious ──────────────────────────────────────────────────────────────
function inv_search($q,$limit) {
    $hosts = ['https://inv.nadeko.net','https://invidious.nerdvpn.de','https://yewtu.be',
              'https://invidious.privacyredirect.com','https://invidious.lunar.icu','https://iv.ggtyler.dev'];
    shuffle($hosts);
    foreach ($hosts as $base) {
        $body = do_curl($base.'/api/v1/search?'.http_build_query(['q'=>$q,'type'=>'video','fields'=>'videoId,title,author,lengthSeconds,videoThumbnails','page'=>1]),7);
        if (!$body) continue;
        $data = json_decode($body,true);
        if (!is_array($data)||empty($data)) continue;
        $r=[];
        foreach (array_slice($data,0,$limit) as $v) {
            $id=$v['videoId']??''; if(!$id)continue;
            $r[]=['id'=>$id,'title'=>$v['title']??'','channel'=>$v['author']??'',
                  'thumb'=>safe_thumb($id,$v['videoThumbnails']??[]),'duration'=>fmt_dur($v['lengthSeconds']??0)];
        }
        if(!empty($r)) return $r;
    }
    return null;
}

// ── 2. Piped ──────────────────────────────────────────────────────────────────
function piped_search($q,$limit) {
    $hosts=['https://pipedapi.kavin.rocks','https://pipedapi.adminforge.de','https://piped-api.garudalinux.org'];
    shuffle($hosts);
    foreach ($hosts as $base) {
        $body=do_curl($base.'/search?'.http_build_query(['q'=>$q,'filter'=>'music_songs']),7);
        if(!$body)continue;
        $data=json_decode($body,true);
        if(empty($data['items']))continue;
        $r=[];
        foreach(array_slice($data['items'],0,$limit) as $v) {
            preg_match('/[?&]v=([a-zA-Z0-9_-]{11})/',$v['url']??'',$m);
            if(empty($m[1])) preg_match('/([a-zA-Z0-9_-]{11})$/',$v['url']??'',$m);
            $id=$m[1]??''; if(!$id)continue;
            $th=$v['thumbnail']??'';
            if(!$th||strpos($th,'http')!==0) $th="https://i.ytimg.com/vi/{$id}/hqdefault.jpg";
            $r[]=['id'=>$id,'title'=>$v['title']??'','channel'=>$v['uploaderName']??'',
                  'thumb'=>$th,'duration'=>fmt_dur($v['duration']??0)];
        }
        if(!empty($r)) return $r;
    }
    return null;
}

// ── 3. Scrape YouTube HTML ────────────────────────────────────────────────────
function yt_scrape($q,$limit) {
    $body=do_curl('https://www.youtube.com/results?'.http_build_query(['search_query'=>$q]),12);
    if(!$body)return null;
    $r=[];
    // Extrai JSON do ytInitialData
    if(preg_match('/ytInitialData\s*=\s*(\{.+?\});\s*(?:<\/script>|var )/',$body,$m)){
        $yt=json_decode($m[1],true);
        $sections=$yt['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents']??[];
        foreach($sections as $sec){
            foreach(($sec['itemSectionRenderer']['contents']??[]) as $item){
                if(empty($item['videoRenderer']))continue;
                $vr=$item['videoRenderer'];
                $id=$vr['videoId']??''; if(!$id)continue;
                $thumb="https://i.ytimg.com/vi/{$id}/hqdefault.jpg";
                // Pega thumb real do videoRenderer
                $thumbs=$vr['thumbnail']['thumbnails']??[];
                foreach(array_reverse($thumbs) as $t){
                    if(!empty($t['url'])&&strpos($t['url'],'ytimg.com')!==false){$thumb=$t['url'];break;}
                }
                $r[]=['id'=>$id,'title'=>$vr['title']['runs'][0]['text']??'','channel'=>$vr['ownerText']['runs'][0]['text']??'',
                      'thumb'=>$thumb,'duration'=>$vr['lengthText']['simpleText']??'--:--'];
                if(count($r)>=$limit)break 2;
            }
        }
    }
    // Fallback regex
    if(empty($r)){
        preg_match_all('/"videoId":"([a-zA-Z0-9_-]{11})"/',$body,$ids);
        $ids=array_unique($ids[1]??[]);
        foreach($ids as $id){
            $r[]=['id'=>$id,'title'=>'Música','channel'=>'','thumb'=>"https://i.ytimg.com/vi/{$id}/hqdefault.jpg",'duration'=>'--:--'];
            if(count($r)>=$limit)break;
        }
    }
    return!empty($r)?$r:null;
}

// ── Cascade ───────────────────────────────────────────────────────────────────
$results = inv_search($q,$limit) ?? piped_search($q,$limit) ?? yt_scrape($q,$limit);
if($results&&count($results)>0){
    // Deduplica
    $seen=[]; $out=[];
    foreach($results as $r){ if(!isset($seen[$r['id']])){$seen[$r['id']]=1;$out[]=$r;} }
    echo json_encode(['success'=>true,'count'=>count($out),'results'=>$out],JSON_UNESCAPED_UNICODE);
}else{
    echo json_encode(['success'=>false,'error'=>'Nenhum resultado encontrado.']);
}
