<?php
use DeeLauLab\AzuraCast\Cover_Finder;

class DeeLauLab_AzuraCast_Controller {

    private static $styles_printed = false;

    public function __construct() {
        add_shortcode( 'azura_history', [ $this, 'handle_shortcode' ] );
        add_action( 'wp_ajax_dllah_refresh_history', [ $this, 'ajax_refresh_history' ] );
        add_action( 'wp_ajax_nopriv_dllah_refresh_history', [ $this, 'ajax_refresh_history' ] );
    }

    private function _get_history_html($url, $station, $count) {
        $settings = wp_parse_args( get_option('deelaulab_ach_settings', []), $this->get_default_settings() );
        $model = new DeeLauLab_AzuraCast_Model();
        
        $api_key = $settings['azuracast_api_key'] ?? '';
        $song_data = $model->get_last_songs($url, $station, $api_key);

        if (is_wp_error($song_data)) {
            return (new DeeLauLab_AzuraCast_View())->render_error( $song_data->get_error_message() );
        }
        
        if (empty($song_data)) {
            $view = new DeeLauLab_AzuraCast_View();
            return $view->render('history-display-v2', ['songs' => [], 'settings' => $settings, 'cover_finder' => new Cover_Finder($settings)]);
        }

        try {
            $cover_finder = new Cover_Finder($settings);
            $view_data = [
                'songs'        => array_slice( $song_data, 0, $count ),
                'settings'     => $settings,
                'cover_finder' => $cover_finder
            ];
            
            return ( new DeeLauLab_AzuraCast_View() )->render( 'history-display-v2', $view_data );

        } catch (Throwable $e) {
            $error_message  = "Ein fataler PHP-Fehler ist aufgetreten und hat die Anzeige verhindert.\n";
            $error_message .= "Fehlermeldung: " . $e->getMessage();
            return '<pre class="dllah-error-message">' . esc_html($error_message) . '</pre>';
        }
    }
    
    public function handle_shortcode( $atts ) {
        wp_enqueue_style('deelaulab-azuracast-history-style', plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/style.css', [], '1.1.0');
        wp_enqueue_script(
            'deelaulab-azuracast-refresher', 
            plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/refresher.js', 
            ['jquery'], '1.1.0', true
        );

        wp_localize_script(
            'deelaulab-azuracast-refresher',
            'dllah_ajax',
            ['ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'dllah_ajax_nonce' )]
        );

        $settings = wp_parse_args( get_option('deelaulab_ach_settings', []), $this->get_default_settings() );
        $atts = shortcode_atts([
            'url'     => $settings['azuracast_url'], 
            'station' => $settings['azuracast_station_id'], 
            'count'   => $settings['history_count']
        ], $atts, 'azura_history');

        if ( empty( $atts['url'] ) || empty( $atts['station'] ) ) {
            return (new DeeLauLab_AzuraCast_View())->render_error('Fehler: Es wurde keine AzuraCast URL und Stations-ID gefunden. Bitte in den Plugin-Einstellungen oder im Shortcode angeben.');
        }

        $output = '';
        if (!self::$styles_printed) {
            $output .= $this->generate_dynamic_styles($settings);
            self::$styles_printed = true;
        }

        if ( !empty($settings['debug_mode']) && $settings['debug_mode'] === '1' ) {
            $output .= '<pre style="background:#fff; color:#000; border:1px solid #000; padding:15px; margin-bottom:20px; text-align:left;">';
            $output .= '<strong>GELADENE EINSTELLUNGEN:</strong><br><br>' . esc_html(print_r($settings, true)) . '</pre>';
        }
        
        $history_html = $this->_get_history_html($atts['url'], $atts['station'], $atts['count']);

        $wrapper_id = 'dllah-wrapper-' . uniqid();
        $output .= sprintf(
            '<div id="%s" class="dllah-wrapper" data-url="%s" data-station="%s" data-count="%d">%s</div>',
            esc_attr($wrapper_id), esc_attr($atts['url']), esc_attr($atts['station']), absint($atts['count']), $history_html
        );

        return $output;
    }

    public function ajax_refresh_history() {
        check_ajax_referer( 'dllah_ajax_nonce', 'nonce' );
        $url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
        $station = isset($_POST['station']) ? sanitize_text_field($_POST['station']) : '';
        $count = isset($_POST['count']) ? absint($_POST['count']) : 10;

        if ( empty($url) || empty($station) ) { wp_send_json_error( 'URL oder Station nicht angegeben.' ); }

        $new_html_content = $this->_get_history_html($url, $station, $count);
        wp_send_json_success( $new_html_content );
    }
    
    public function get_default_settings() { 
        return [ 
            'azuracast_url' => '',
            'azuracast_station_id' => '',
            'azuracast_api_key' => '',
            'spotify_client_id' => '', 
            'spotify_client_secret' => '', 
            'lastfm_api_key' => '', 
            'fallback_cover_url' => '', 
            'bg_color_main' => '', 
            'bg_color_song' => '', 
            'color_title' => '', 
            'color_artist' => '', 
            'color_time' => '', 
            'cover_size' => 80, 
            'history_count' => 10, 
            'show_icons' => ['youtube' => '1', 'soundcloud' => '1', 'spotify' => '1', 'amazon' => '1', 'itunes' => '1'], 
            'debug_mode' => '0' 
        ]; 
    }
    
    public function generate_dynamic_styles($settings) { $css = '<style>'; $add_rule = function($selector, $property, $value) use (&$css) { if (!empty($value)) { $css .= sprintf('%s { %s: %s !important; }', $selector, $property, esc_attr($value)); } }; $add_rule('.dllah-wrapper', 'background-color', $settings['bg_color_main']); $add_rule('.dllah-song-entry', 'background-color', $settings['bg_color_song']); $add_rule('.dllah-song-details .dllah-time-title strong', 'color', $settings['color_title']); $add_rule('.dllah-song-details .dllah-artist', 'color', $settings['color_artist']); $add_rule('.dllah-song-details .dllah-time-title', 'color', $settings['color_time']); $add_rule('.dllah-song-cover', 'width', $settings['cover_size'] . 'px'); $css .= '</style>'; return $css; }
}