<?php
header('Content-Type: application/json');
require_once __DIR__.'/../includes/pexels.php';

$action = $_GET['action'] ?? 'multiple';

if ($action === 'multiple') {
    $qs = isset($_GET['queries']) ? explode(',', $_GET['queries']) : ['trading chart', 'bitcoin tech', 'ethereum crypto'];
    $out = [];
    foreach ($qs as $q) {
        $u = 'https://api.pexels.com/v1/search?query=' . urlencode(trim($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'];
            $filename = $p['id'] . '.jpg';
            $dest = __DIR__ . '/../assets/images/pexels/' . $filename;
            
            if (!file_exists($dest)) {
                download_to($src, $dest);
            }
            
            $out[] = [
                'src' => 'assets/images/pexels/' . $filename,
                'photographer' => $p['photographer'] ?? 'Unknown',
                'photographer_url' => $p['photographer_url'] ?? '',
                'title' => trim($q)
            ];
        } else {
            // Fallback
            $out[] = [
                'src' => 'https://picsum.photos/1200/400?random=' . rand(1, 100),
                'photographer' => 'Random',
                'photographer_url' => '#',
                'title' => trim($q)
            ];
        }
    }
    echo json_encode($out);
}
