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

if (!isset($_GET['action'])) {
    echo json_encode(['error' => 'Action not specified']);
    exit;
}

$action = $_GET['action'];

if ($action === 'image') {
    $q = isset($_GET['query']) ? $_GET['query'] : 'nature';
    $orientation = isset($_GET['orientation']) ? $_GET['orientation'] : 'portrait';
    $url = 'https://api.pexels.com/v1/search?query=' . urlencode($q) . '&orientation=' . urlencode($orientation) . '&per_page=1&page=1';
    $data = pexels_get($url);
    if (!$data || empty($data['photos'])) { echo json_encode(['error'=>'Failed to fetch image']); exit; }
    $photo = $data['photos'][0];
    $src = $photo['src']['large2x'] ?? ($photo['src']['large'] ?? $photo['src']['original']);
    $target = __DIR__ . '/../assets/images/pexels/' . $photo['id'] . '.jpg';
    download_to($src, $target);
    // Return minimal info and local relative path
    echo json_encode([
      'id' => $photo['id'],
      'local' => 'assets/images/pexels/' . $photo['id'] . '.jpg',
      'photographer' => $photo['photographer'] ?? null,
      'photographer_url' => $photo['photographer_url'] ?? null,
    ]);
} elseif ($action === 'multiple') {
    $qs = isset($_GET['queries']) ? explode(',', $_GET['queries']) : ['home','apple','pizza','mountains','cat'];
    $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);
} else {
    echo json_encode(['error' => 'Invalid action']);
    exit;
}
