'Failed to fetch image from Pexels.']); exit; } $photo = $data['photos'][0]; $src = $photo['src']['large2x'] ?? ($photo['src']['large'] ?? $photo['src']['original']); $filename = $photo['id'] . '.jpg'; $target_path = $cache_dir . $filename; // Download if it doesn't exist if (!file_exists($target_path)) { if (!download_to($src, $target_path)) { http_response_code(500); echo json_encode(['error' => 'Failed to download and save image.']); exit; } } // Return minimal info and local relative path echo json_encode([ 'id' => $photo['id'], 'local_path' => 'assets/images/pexels/' . $filename, 'photographer' => $photo['photographer'] ?? null, 'photographer_url' => $photo['photographer_url'] ?? null, 'alt' => $photo['alt'] ?? 'Image related to ' . $query, ]);