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

// --- Configuration ---
$query = isset($_GET['query']) ? $_GET['query'] : 'hurricane';
$orientation = isset($_GET['orientation']) ? $_GET['orientation'] : 'landscape';
$cache_dir = __DIR__ . '/../assets/images/pexels/';
// --- End Configuration ---

// Ensure cache directory exists
if (!is_dir($cache_dir)) {
    mkdir($cache_dir, 0775, true);
}

$url = 'https://api.pexels.com/v1/search?query=' . urlencode($query) . '&orientation=' . urlencode($orientation) . '&per_page=1&page=1';
$data = pexels_get($url);

if (!$data || empty($data['photos'])) {
    http_response_code(500);
    echo json_encode(['error' => '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,
]);
