<?php
// GIF search proxy. Keeps the API key server-side (out of the browser), avoids
// CORS, and normalizes Klipy / Tenor / GIPHY responses to a single shape:
//   { ok:true, gifs:[ { preview, full } ] }
// The client calls:  gif.php            -> trending
//                     gif.php?q=happy    -> search
require_once __DIR__ . '/config.php';
must_auth();

if (!defined('GIF_API_KEY') || GIF_API_KEY === '') {
    die(json_encode(array(
        'error'   => 'no_key',
        'message' => 'GIF search is not configured. Add a free GIF API key (KLIPY is recommended — it is what WhatsApp uses) in api/config.php (GIF_API_KEY / GIF_PROVIDER).'
    )));
}

$q     = isset($_GET['q']) ? trim($_GET['q']) : '';
$limit = 24;
$key   = GIF_API_KEY;
$prov  = strtolower(GIF_PROVIDER);

function http_get_json($url) {
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 8,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_USERAGENT      => 'Spaceship/1.0'
        ));
        $body = curl_exec($ch);
        $err  = curl_error($ch);
        curl_close($ch);
        if ($body === false) return array(null, $err ?: 'request failed');
    } else {
        $ctx  = stream_context_create(array('http' => array('timeout' => 8, 'header' => "User-Agent: Spaceship/1.0\r\n")));
        $body = @file_get_contents($url, false, $ctx);
        if ($body === false) return array(null, 'request failed (enable cURL or allow_url_fopen)');
    }
    $data = json_decode($body, true);
    if (!is_array($data)) return array(null, 'bad response');
    return array($data, null);
}

function first_url(/* ...candidates */) {
    foreach (func_get_args() as $u) {
        if (is_string($u) && $u !== '') return $u;
    }
    return '';
}

$gifs = array();

if ($prov === 'giphy') {
    $base = 'https://api.giphy.com/v1/gifs/' . ($q !== '' ? 'search' : 'trending');
    $url  = $base . '?api_key=' . urlencode($key) . '&limit=' . $limit . '&rating=pg&bundle=fixed_height';
    if ($q !== '') $url .= '&q=' . urlencode($q);
    list($data, $err) = http_get_json($url);
    if ($err) die(json_encode(array('error' => 'upstream', 'message' => $err)));
    foreach ((isset($data['data']) ? $data['data'] : array()) as $it) {
        $im = isset($it['images']) ? $it['images'] : array();
        $preview = first_url(
            isset($im['fixed_height_small']['url']) ? $im['fixed_height_small']['url'] : '',
            isset($im['fixed_height']['url']) ? $im['fixed_height']['url'] : ''
        );
        $full = first_url(
            isset($im['fixed_height']['url']) ? $im['fixed_height']['url'] : '',
            isset($im['original']['url']) ? $im['original']['url'] : '',
            $preview
        );
        if ($preview) $gifs[] = array('preview' => $preview, 'full' => $full);
    }
} elseif ($prov === 'tenor') {
    $base = 'https://tenor.googleapis.com/v2/' . ($q !== '' ? 'search' : 'featured');
    $url  = $base . '?key=' . urlencode($key) . '&client_key=spaceship&limit=' . $limit
          . '&media_filter=tinygif,gif&contentfilter=high';
    if ($q !== '') $url .= '&q=' . urlencode($q);
    list($data, $err) = http_get_json($url);
    if ($err) die(json_encode(array('error' => 'upstream', 'message' => $err)));
    foreach ((isset($data['results']) ? $data['results'] : array()) as $it) {
        $mf = isset($it['media_formats']) ? $it['media_formats'] : array();
        $preview = first_url(
            isset($mf['tinygif']['url']) ? $mf['tinygif']['url'] : '',
            isset($mf['gif']['url']) ? $mf['gif']['url'] : ''
        );
        $full = first_url(
            isset($mf['gif']['url']) ? $mf['gif']['url'] : '',
            $preview
        );
        if ($preview) $gifs[] = array('preview' => $preview, 'full' => $full);
    }
} else { // klipy (default; what WhatsApp uses)
    // KLIPY mirrors Tenor's structure; media lives under each item's "files".
    $path = ($q !== '' ? 'search' : 'trending');
    $url  = 'https://api.klipy.com/api/v1/' . urlencode($key) . '/gifs/' . $path
          . '?per_page=' . $limit . '&page=1&content_filter=high';
    if ($q !== '') $url .= '&q=' . urlencode($q);
    list($data, $err) = http_get_json($url);
    if ($err) die(json_encode(array('error' => 'upstream', 'message' => $err)));
    // KLIPY wraps results in data.data (paginated). Be liberal about shape.
    $items = array();
    if (isset($data['data']['data']) && is_array($data['data']['data']))      $items = $data['data']['data'];
    elseif (isset($data['data']) && is_array($data['data']))                   $items = $data['data'];
    elseif (isset($data['results']) && is_array($data['results']))             $items = $data['results'];
    foreach ($items as $it) {
        $files = isset($it['file']) ? $it['file'] : (isset($it['files']) ? $it['files'] : array());
        // Common KLIPY layout: file.{sm,md,hd}.gif.url
        $preview = first_url(
            isset($files['sm']['gif']['url']) ? $files['sm']['gif']['url'] : '',
            isset($files['md']['gif']['url']) ? $files['md']['gif']['url'] : '',
            isset($it['url']) ? $it['url'] : ''
        );
        $full = first_url(
            isset($files['md']['gif']['url']) ? $files['md']['gif']['url'] : '',
            isset($files['hd']['gif']['url']) ? $files['hd']['gif']['url'] : '',
            $preview
        );
        if ($preview) $gifs[] = array('preview' => $preview, 'full' => $full);
    }
}

ok(array('gifs' => $gifs));
