<?php

namespace Breakdance\AI;

add_action('breakdance_loaded', function () {
    \Breakdance\AJAX\register_handler(
        'breakdance_ai_talk_to_unsplash',
        'Breakdance\AI\talkToUnsplash',
        'edit',
        false,
        [
            'args' => [
                'prompt' => FILTER_UNSAFE_RAW
            ]
        ]
    );
});

function talkToUnsplash() {
    $key = \Breakdance\APIKeys\getKey('unsplash');

    if (!$key) {
        return ['error' => 'Please enter an Unsplash key in the settings page.'];
    }

    $url = 'https://api.unsplash.com/search/photos';
    $params = [
        'client_id' => $key,
        'count' => $_POST['limit'] ?? 10,
        'query' => $_POST['prompt'] ?? 'People'
    ];

    if (isset($_POST['orientation']) && !empty($_POST['orientation'])) {
        $params['orientation'] = $_POST['orientation'];
    }

    $request = wp_remote_get($url . '?' . http_build_query($params));
    $body = wp_remote_retrieve_body($request);
    $response = json_decode($body, true);

    if (is_wp_error($body)) {
        return ['type' => 'error', 'message' => 'Could not fetch images from Unsplash.'];
    }

    return [
        'data' => $response['results']
    ];
}
