<?php
/*
desenvolvedor: luciano donizeti
mania de script: www.maniadescript.com.br
whatsapp 43998240911
*/

session_start();
header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION["usuario"]) || !isset($_SESSION["user_id"])) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'message' => 'Sessão expirada. Faça login novamente.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$query = trim((string)($_GET['q'] ?? ''));
if ($query === '' || strlen($query) < 2) {
    echo json_encode(['ok' => false, 'message' => 'Digite pelo menos 2 caracteres para buscar imagens.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$query = preg_replace('/\s+/', ' ', $query);
$query = substr($query, 0, 90);
$limit = min(max((int)($_GET['limit'] ?? 12), 4), 18);

function bg_http_get(string $url, int $timeout = 12) {
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_CONNECTTIMEOUT => 7,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; BannerBackgroundSearch/1.0)',
            CURLOPT_HTTPHEADER => ['Accept: application/json,text/html,*/*'],
        ]);
        $body = curl_exec($ch);
        $http = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        curl_close($ch);
        return ($body !== false && $http >= 200 && $http < 400) ? $body : false;
    }
    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'timeout' => $timeout,
            'header' => "User-Agent: Mozilla/5.0 (compatible; BannerBackgroundSearch/1.0)\r\nAccept: application/json,text/html,*/*\r\n",
        ],
        'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
    ]);
    $body = @file_get_contents($url, false, $context);
    return $body === false ? false : $body;
}

function bg_absolute_url(string $url): string {
    $url = trim($url);
    if ($url === '') { return ''; }
    if (strpos($url, '//') === 0) { return 'https:' . $url; }
    return $url;
}

function bg_add_result(array &$results, array $item, int $limit): void {
    $image = bg_absolute_url((string)($item['image'] ?? ''));
    $thumb = bg_absolute_url((string)($item['thumb'] ?? $image));
    if (!filter_var($image, FILTER_VALIDATE_URL) || !filter_var($thumb, FILTER_VALIDATE_URL)) { return; }
    foreach ($results as $existing) {
        if (($existing['image'] ?? '') === $image) { return; }
    }
    $results[] = [
        'title' => trim((string)($item['title'] ?? 'Imagem encontrada')),
        'image' => $image,
        'thumb' => $thumb,
        'source' => trim((string)($item['source'] ?? 'Internet')),
    ];
    if (count($results) > $limit) { array_pop($results); }
}

function bg_search_duckduckgo(string $query, int $limit): array {
    $results = [];
    $html = bg_http_get('https://duckduckgo.com/?q=' . rawurlencode($query) . '&iax=images&ia=images');
    if ($html === false) { return $results; }

    $vqd = '';
    if (preg_match('/vqd=["\']?([0-9-]+)["\']?/', $html, $m)) {
        $vqd = $m[1];
    } elseif (preg_match('/"vqd":"([^"]+)"/', $html, $m)) {
        $vqd = $m[1];
    }
    if ($vqd === '') { return $results; }

    $url = 'https://duckduckgo.com/i.js?l=br-pt&o=json&q=' . rawurlencode($query) . '&vqd=' . rawurlencode($vqd) . '&f=,,,&p=1';
    $json = bg_http_get($url);
    $data = $json ? json_decode($json, true) : null;
    if (!is_array($data) || empty($data['results']) || !is_array($data['results'])) { return $results; }

    foreach ($data['results'] as $row) {
        bg_add_result($results, [
            'title' => $row['title'] ?? 'Imagem encontrada',
            'image' => $row['image'] ?? '',
            'thumb' => $row['thumbnail'] ?? ($row['image'] ?? ''),
            'source' => parse_url((string)($row['url'] ?? ''), PHP_URL_HOST) ?: 'DuckDuckGo',
        ], $limit);
        if (count($results) >= $limit) { break; }
    }
    return $results;
}

function bg_search_wikimedia(string $query, int $limit): array {
    $results = [];
    $params = [
        'action' => 'query',
        'format' => 'json',
        'generator' => 'search',
        'gsrnamespace' => '6',
        'gsrsearch' => $query,
        'gsrlimit' => (string)min($limit * 2, 30),
        'prop' => 'imageinfo',
        'iiprop' => 'url|mime',
        'iiurlwidth' => '1200',
        'iiurlheight' => '1600',
        'origin' => '*',
    ];
    $json = bg_http_get('https://commons.wikimedia.org/w/api.php?' . http_build_query($params));
    $data = $json ? json_decode($json, true) : null;
    if (!is_array($data) || empty($data['query']['pages'])) { return $results; }

    foreach ($data['query']['pages'] as $page) {
        $info = $page['imageinfo'][0] ?? [];
        $mime = strtolower((string)($info['mime'] ?? ''));
        if (!in_array($mime, ['image/jpeg', 'image/png', 'image/webp'], true)) { continue; }
        bg_add_result($results, [
            'title' => str_replace('File:', '', (string)($page['title'] ?? 'Imagem Wikimedia')),
            'image' => $info['url'] ?? '',
            'thumb' => $info['thumburl'] ?? ($info['url'] ?? ''),
            'source' => 'Wikimedia Commons',
        ], $limit);
        if (count($results) >= $limit) { break; }
    }
    return $results;
}

$results = bg_search_duckduckgo($query, $limit);
if (count($results) < 4) {
    foreach (bg_search_wikimedia($query, $limit) as $item) {
        bg_add_result($results, $item, $limit);
        if (count($results) >= $limit) { break; }
    }
}

echo json_encode([
    'ok' => true,
    'query' => $query,
    'count' => count($results),
    'results' => $results,
    'message' => count($results) ? 'Imagens encontradas.' : 'Nenhuma imagem encontrada para essa busca.',
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
