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

$query = isset($_GET["query"]) ? $_GET["query"] : "abstract music background";
// We want a nice, large background image
$url = "https://api.pexels.com/v1/search?query=" . urlencode($query) . "&orientation=landscape&per_page=1&page=" . rand(1, 20);
$data = pexels_get($url);

if ($data && !empty($data["photos"])) {
    $photo = $data["photos"][0];
    echo json_encode([
        "success" => true,
        "url" => $photo["src"]["large2x"] ?? $photo["src"]["large"],
        "photographer" => $photo["photographer"]
    ]);
} else {
    // Fallback if search fails
    echo json_encode([
        "success" => false,
        "error" => "No images found"
    ]);
}