<?php
header('Content-Type: application/json');
require_once __DIR__.'/../includes/pexels.php';
$qs = isset($_GET['queries']) ? explode(',', $_GET['queries']) : ['person,face','city,street','nature,mountain','animal,cat','food,pizza'];
$out = [];
foreach ($qs as $q) {
  $u = 'https://api.pexels.com/v1/search?query=' . urlencode(trim($q)) . '&orientation=square&per_page=3&page=1';
  $d = pexels_get($u);
  if ($d && !empty($d['photos'])) {
    foreach($d['photos'] as $p) {
        $src = $p['src']['large'] ?? null;
        $dest = __DIR__.'/../assets/images/pexels/'.$p['id'].'.jpg';
        if ($src && !file_exists($dest)) {
            download_to($src, $dest);
        }
        $out[] = [
            'src' => 'assets/images/pexels/'.$p['id'].'.jpg',
            'photographer' => $p['photographer'] ?? 'Unknown',
            'photographer_url' => $p['photographer_url'] ?? '',
            'alt' => $p['alt'] ?? 'Photo by '.$p['photographer'],
        ];
    }
  } else {
    // Fallback: Picsum
    $out[] = [
      'src' => 'https://picsum.photos/600/600',
      'photographer' => 'Random Picsum',
      'photographer_url' => 'https://picsum.photos/',
      'alt' => 'Random placeholder image'
    ];
  }
}
echo json_encode($out);
