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

$action = $_GET['action'] ?? 'search';

if ($action === 'search') {
    $q = $_GET['query'] ?? 'avatar';
    $url = 'https://api.pexels.com/v1/search?query=' . urlencode($q) . '&per_page=12&page=1';
    $data = pexels_get($url);
    if (!$data) {
        echo json_encode(['error' => 'Failed to fetch images']);
        exit;
    }
    
    $results = [];
    foreach ($data['photos'] as $photo) {
        $results[] = [
            'id' => $photo['id'],
            'url' => $photo['src']['medium'],
            'photographer' => $photo['photographer']
        ];
    }
    echo json_encode($results);
    exit;
}
