<?php
class DeeLauLab_AzuraCast_Model {
    public function get_last_songs( $azura_url, $station_id, $api_key = '' ) {
        $azura_url = rtrim( $azura_url, '/' );
        if (empty($azura_url) || empty($station_id)) {
            return new WP_Error('missing_params', 'AzuraCast URL oder Stations-ID fehlen.');
        }
        
        $transient_key = 'dllah_history_' . md5( $azura_url . $station_id );
        $cached_songs = get_transient( $transient_key );

        if ( false !== $cached_songs ) { return $cached_songs; }

        $api_url = "{$azura_url}/api/station/{$station_id}/history";
        
        $args = ['timeout' => 10];
        if ( ! empty( $api_key ) ) {
            $args['headers'] = ['X-API-Key' => $api_key];
        }

        $response = wp_remote_get( $api_url, $args );

        if ( is_wp_error( $response ) ) {
            return new WP_Error( 'api_error', 'Die AzuraCast API ist derzeit nicht erreichbar.' );
        }

        $response_code = wp_remote_retrieve_response_code( $response );
        if ( 200 !== $response_code ) {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $message = $body['message'] ?? 'Station nicht gefunden oder API-Schlüssel ungültig.';
            set_transient( $transient_key, [], 60 );
            return new WP_Error( 'invalid_station', $message );
        }

        $songs = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( ! is_array( $songs ) ) {
            set_transient( $transient_key, [], 60 );
            return new WP_Error( 'invalid_data', 'Ungültige Daten von der AzuraCast-API empfangen.' );
        }

        set_transient( $transient_key, $songs, 30 );
        return $songs;
    }
}