<?php
  header('Content-Type: application/json');
  require_once __DIR__.'/../includes/pexels.php';
  $qs = isset($_GET['queries']) ? explode(',', $_GET['queries']) : ['professional portrait','man smiling','woman smiling'];
  $out = [];
  foreach ($qs as $q) {
    $u = 'https://api.pexels.com/v1/search?query=' . urlencode(trim($q)) . '&orientation=square&per_page=1&page=1';
    $d = pexels_get($u);
    if ($d && !empty($d['photos'])) {
      $p = $d['photos'][0];
      $src = $p['src']['original'] ?? null;
      $dest = __DIR__.'/../assets/images/pexels/'.$p['id'].'.jpg';
      if ($src) download_to($src, $dest);
      $out[] = [
        'src' => 'assets/images/pexels/'.$p['id'].'.jpg',
        'photographer' => $p['photographer'] ?? 'Unknown',
        'photographer_url' => $p['photographer_url'] ?? '',
      ];
    } else {
      // Fallback: Picsum
      $out[] = [
        'src' => 'https://picsum.photos/600',
        'photographer' => 'Random Picsum',
        'photographer_url' => 'https://picsum.photos/'
      ];
    }
  }
  echo json_encode($out);
  ?>