<?php
header('Content-Type: application/json');

function pexels_key() {
    $k = getenv('PEXELS_KEY');
    return $k && strlen($k) > 0 ? $k : 'Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18';
}

function pexels_get($url) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [ 'Authorization: '. pexels_key() ],
        CURLOPT_TIMEOUT => 15,
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($code >= 200 && $code < 300 && $resp) return json_decode($resp, true);
    return null;
}

function download_to($srcUrl, $destPath) {
    $data = @file_get_contents($srcUrl);
    if ($data === false) return false;
    if (!is_dir(dirname($destPath))) mkdir(dirname($destPath), 0775, true);
    return file_put_contents($destPath, $data) !== false;
}

$queries = ['cryptocurrency', 'bitcoin mining', 'blockchain technology', 'digital finance', 'trading floor'];
$out = [];

if (!is_dir(__DIR__ . '/../assets/images/hero')) {
    mkdir(__DIR__ . '/../assets/images/hero', 0775, true);
}

foreach ($queries as $index => $q) {
    $filename = 'hero_' . ($index + 1) . '.jpg';
    $target = __DIR__ . '/../assets/images/hero/' . $filename;
    
    // Cache for 24 hours
    if (!file_exists($target) || (time() - filemtime($target) > 86400)) {
        $u = 'https://api.pexels.com/v1/search?query=' . urlencode($q) . '&orientation=landscape&per_page=1&page=1';
        $d = pexels_get($u);
        if ($d && !empty($d['photos'])) {
            $p = $d['photos'][0];
            $src = $p['src']['large2x'] ?? $p['src']['original'];
            download_to($src, $target);
        }
    }
    
    if (file_exists($target)) {
        $out[] = 'assets/images/hero/' . $filename;
    } else {
        // Fallback to picsum if pexels fails
        $out[] = 'https://picsum.photos/1200/600?random=' . $index;
    }
}

echo json_encode(['success' => true, 'images' => $out]);
