<?php
defined( 'ABSPATH' ) || exit;

class NASEO_Image_Fetcher {

    private string $api_key;
    private string $api_url = 'https://api.pexels.com/v1/search';

    public function __construct() {
        $this->api_key = get_option( 'naseo_pexels_api_key', '' );
    }

    /**
     * Знаходить фото і завантажує як медіафайл WP
     * Повертає attachment_id або false
     */
    public function fetch_and_attach( string $keyword, int $post_id ) {
        if ( empty( $this->api_key ) ) return false;

        $photo = $this->search_photo( $keyword );
        if ( ! $photo ) return false;

        return $this->upload_to_media( $photo, $post_id, $keyword );
    }

    private function search_photo( string $keyword ) {
        $response = wp_remote_get( add_query_arg( [
            'query'    => urlencode( $keyword ),
            'per_page' => 5,
            'orientation' => 'landscape',
        ], $this->api_url ), [
            'timeout' => 15,
            'headers' => [ 'Authorization' => $this->api_key ],
        ] );

        if ( is_wp_error( $response ) ) return false;

        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
        $photos = $body['photos'] ?? [];

        if ( empty( $photos ) ) return false;

        // Беремо випадкове з перших 5
        $photo = $photos[ array_rand( $photos ) ];

        return [
            'url'          => $photo['src']['large2x'] ?? $photo['src']['large'],
            'photographer' => $photo['photographer'] ?? '',
            'alt'          => $photo['alt'] ?? $keyword,
        ];
    }

    private function upload_to_media( array $photo, int $post_id, string $keyword ) {
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        $tmp = download_url( $photo['url'] );
        if ( is_wp_error( $tmp ) ) return false;

        $filename  = sanitize_title( $keyword ) . '-' . time() . '.jpg';
        $file_array = [
            'name'     => $filename,
            'tmp_name' => $tmp,
        ];

        $attachment_id = media_handle_sideload( $file_array, $post_id, $photo['alt'] );

        wp_delete_file( $tmp );

        if ( is_wp_error( $attachment_id ) ) return false;

        // Встановлюємо alt text
        update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $photo['alt'] ) );

        // Додаємо credit в caption
        if ( $photo['photographer'] ) {
            $attachment = get_post( $attachment_id );
            wp_update_post( [
                'ID'           => $attachment_id,
                'post_excerpt' => 'Photo by ' . $photo['photographer'] . ' on Pexels',
            ] );
        }

        return $attachment_id;
    }
}
