<?php
class DeeLauLab_AzuraCast_Admin {

    private $option_name = 'deelaulab_ach_settings';

    public function __construct() {
        add_action('admin_menu', [$this, 'add_plugin_page']);
        add_action('admin_init', [$this, 'page_init']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
    }

    public function enqueue_admin_assets($hook) {
        if ($hook != 'toplevel_page_deelaulab-azuracast-history') { return; }
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_style('deelaulab-azuracast-admin-style', plugin_dir_url(dirname(__FILE__)) . 'assets/css/admin-style.css', [], '1.1.0');
        wp_enqueue_script('wp-color-picker-alpha', plugin_dir_url(dirname(__FILE__)) . 'assets/js/wp-color-picker-alpha.js', ['jquery', 'wp-color-picker'], '3.0.4', true);
        wp_add_inline_script('wp-color-picker-alpha', 'jQuery(document).ready(function($){$(".wp-color-picker-field").wpColorPicker({palettes: true});});');
    }

    public function add_plugin_page() {
        add_menu_page('AzuraCast History Einstellungen', 'DLL-AzuraCast', 'manage_options', 'deelaulab-azuracast-history', [$this, 'create_admin_page'], 'dashicons-format-audio', 58);
    }

    public function create_admin_page() {
        if (isset($_GET['settings-updated'])) { add_settings_error('dllah_messages', 'dllah_message', __('Einstellungen gespeichert.'), 'updated'); }
        if (isset($_GET['cache-cleared'])) {
            $count = isset($_GET['count']) ? absint($_GET['count']) : 0;
            add_settings_error('dllah_messages', 'dllah_message', sprintf(__('Cover-Cache erfolgreich geleert. %d Einträge wurden entfernt.'), $count), 'updated');
        }
        settings_errors('dllah_messages');
        ?>
        <div class="wrap dllah-settings-wrapper">
            <h1>AzuraCast History Einstellungen</h1>
            <form method="post" action="options.php">
                <?php settings_fields('deelaulab_ach_option_group'); do_settings_sections('deelaulab-ach-admin'); submit_button(); ?>
            </form>
            <hr>
            <h2>Cache-Verwaltung</h2>
            <p>Leeren Sie den Cache, wenn ein Cover nicht korrekt angezeigt wird.</p>
            <form method="post" action="">
                <?php wp_nonce_field('dllah_clear_cache', 'dllah_clear_cache_nonce'); ?>
                <input type="hidden" name="action" value="dllah_clear_cache">
                <?php submit_button('Cover-Cache jetzt leeren', 'delete', 'submit_clear_cache'); ?>
            </form>
        </div>
        <?php
    }

    private function handle_cache_clearing() {
        if (isset($_POST['action']) && $_POST['action'] === 'dllah_clear_cache' && isset($_POST['dllah_clear_cache_nonce']) && wp_verify_nonce($_POST['dllah_clear_cache_nonce'], 'dllah_clear_cache')) {
            if (!current_user_can('manage_options')) return;
            global $wpdb;
            $prefix = '_transient_dllfh_cover_'; 
            $sql = "SELECT `option_name` FROM `{$wpdb->options}` WHERE `option_name` LIKE %s";
            $transients = $wpdb->get_col($wpdb->prepare($sql, $wpdb->esc_like($prefix) . '%'));
            $count = 0;
            foreach ($transients as $transient) { if (delete_transient(str_replace('_transient_', '', $transient))) { $count++; } }
            wp_redirect(admin_url('admin.php?page=deelaulab-azuracast-history&cache-cleared=true&count=' . $count));
            exit;
        }
    }

    public function page_init() {
        $this->handle_cache_clearing();
        register_setting('deelaulab_ach_option_group', $this->option_name, [$this, 'sanitize']);
        add_settings_section('setting_section_api', 'Grundeinstellungen', null, 'deelaulab-ach-admin');
        add_settings_section('setting_section_fallback', 'Fallback Cover-Suche (Optional)', null, 'deelaulab-ach-admin');
        add_settings_section('setting_section_layout', 'Layout & Inhalt', null, 'deelaulab-ach-admin');
        add_settings_section('setting_section_colors', 'Farb-Einstellungen', null, 'deelaulab-ach-admin');
        add_settings_section('setting_section_debug', 'Fehlersuche (Debug)', null, 'deelaulab-ach-admin');

        $fields = [
            'azuracast_url'       => ['section' => 'setting_section_api', 'title' => 'AzuraCast URL', 'type' => 'text', 'desc' => 'Die Haupt-URL deiner AzuraCast-Instanz (z.B. https://dein-radio.de).'],
            'azuracast_station_id' => ['section' => 'setting_section_api', 'title' => 'Stations-Kurzname', 'type' => 'text', 'desc' => 'Der Kurzname/ID deiner Station (z.B. radio_1 oder hauptsender).'],
            'azuracast_api_key'   => ['section' => 'setting_section_api', 'title' => 'AzuraCast API-Schlüssel', 'type' => 'password', 'desc' => 'Optional: Dein API-Schlüssel für authentifizierte Abfragen.'],
            'spotify_client_id'   => ['section' => 'setting_section_fallback', 'title' => 'Spotify Client ID', 'type' => 'text'],
            'spotify_client_secret' => ['section' => 'setting_section_fallback', 'title' => 'Spotify Client Secret', 'type' => 'password'],
            'lastfm_api_key'      => ['section' => 'setting_section_fallback', 'title' => 'Last.fm API Key', 'type' => 'text'],
            'fallback_cover_url'  => ['section' => 'setting_section_fallback', 'title' => 'Absolutes Fallback Cover', 'type' => 'text', 'desc' => 'Wird angezeigt, wenn absolut kein Cover gefunden wird.'],
            'history_count'       => ['section' => 'setting_section_layout', 'title' => 'Anzahl Einträge (1-20)', 'type' => 'number_range', 'min' => 1, 'max' => 20],
            'cover_size'          => ['section' => 'setting_section_layout', 'title' => 'Cover-Größe (in px)', 'type' => 'number', 'desc' => 'Empfehlung: 80'],
            'show_icons'          => ['section' => 'setting_section_layout', 'title' => 'Angezeigte Icons', 'type' => 'icons'],
            'bg_color_main'       => ['section' => 'setting_section_colors', 'title' => 'Gesamt Hintergrund', 'type' => 'color'],
            'bg_color_song'       => ['section' => 'setting_section_colors', 'title' => 'Song Hintergrund', 'type' => 'color'],
            'color_title'         => ['section' => 'setting_section_colors', 'title' => 'Song-Titel Schriftfarbe', 'type' => 'color'],
            'color_artist'        => ['section' => 'setting_section_colors', 'title' => 'Interpret Schriftfarbe', 'type' => 'color'],
            'color_time'          => ['section' => 'setting_section_colors', 'title' => 'Zeit Schriftfarbe', 'type' => 'color'],
            'debug_mode'          => ['section' => 'setting_section_debug', 'title' => 'Debug-Modus aktivieren', 'type' => 'checkbox', 'desc' => 'Zeigt die geladenen Einstellungen direkt über dem Shortcode an.']
        ];
        foreach ($fields as $id => $field) { add_settings_field($id, $field['title'], [$this, 'render_field'], 'deelaulab-ach-admin', $field['section'], ['id' => $id, 'field' => $field]); }
    }

    public function sanitize($input) {
        if (!is_array($input)) { return []; }
        $sanitized_output = [];
        $defaults = (new DeeLauLab_AzuraCast_Controller())->get_default_settings();
        $merged_input = wp_parse_args($input, $defaults);
        
        $sanitized_output['azuracast_url'] = esc_url_raw(trim($merged_input['azuracast_url']));
        $sanitized_output['azuracast_station_id'] = sanitize_text_field($merged_input['azuracast_station_id']);
        $sanitized_output['azuracast_api_key'] = sanitize_text_field($merged_input['azuracast_api_key']);
        $sanitized_output['spotify_client_id'] = sanitize_text_field($merged_input['spotify_client_id']);
        $sanitized_output['spotify_client_secret'] = sanitize_text_field($merged_input['spotify_client_secret']);
        $sanitized_output['lastfm_api_key'] = sanitize_text_field($merged_input['lastfm_api_key']);
        $sanitized_output['fallback_cover_url'] = esc_url_raw($merged_input['fallback_cover_url']);
        $sanitized_output['bg_color_main'] = sanitize_text_field($merged_input['bg_color_main']);
        $sanitized_output['bg_color_song'] = sanitize_text_field($merged_input['bg_color_song']);
        $sanitized_output['color_title'] = sanitize_text_field($merged_input['color_title']);
        $sanitized_output['color_artist'] = sanitize_text_field($merged_input['color_artist']);
        $sanitized_output['color_time'] = sanitize_text_field($merged_input['color_time']);
        $sanitized_output['cover_size'] = absint($merged_input['cover_size']);
        $sanitized_output['history_count'] = absint($merged_input['history_count']);
        if ($sanitized_output['history_count'] > 20) $sanitized_output['history_count'] = 20;
        if ($sanitized_output['history_count'] < 1) $sanitized_output['history_count'] = 1;
        $sanitized_output['show_icons'] = isset($input['show_icons']) && is_array($input['show_icons']) ? array_keys($input['show_icons']) : [];
        $sanitized_output['debug_mode'] = isset($input['debug_mode']) && $input['debug_mode'] === '1' ? '1' : '0';
        
        return $sanitized_output;
    }

    public function render_field($args) {
        $id = $args['id'];
        $field = $args['field'];
        $defaults = (new DeeLauLab_AzuraCast_Controller())->get_default_settings();
        $options = get_option($this->option_name, $defaults);
        $value = $options[$id] ?? ($defaults[$id] ?? '');

        switch ($field['type']) {
            case 'text':
                printf('<input type="text" id="%s" name="%s[%s]" value="%s" class="regular-text" />', $id, $this->option_name, $id, esc_attr($value));
                break;
            case 'password':
                printf('<input type="password" id="%s" name="%s[%s]" value="%s" class="regular-text" />', $id, $this->option_name, $id, esc_attr($value));
                break;
            case 'color':
                printf('<input type="text" id="%s" name="%s[%s]" value="%s" class="wp-color-picker-field" data-alpha-enabled="true" />', $id, $this->option_name, $id, esc_attr($value));
                break;
            case 'number':
                printf('<input type="number" id="%s" name="%s[%s]" value="%s" />', $id, $this->option_name, $id, esc_attr($value));
                break;
            case 'number_range':
                printf('<input type="number" id="%s" name="%s[%s]" value="%s" min="%d" max="%d" />', $id, $this->option_name, $id, esc_attr($value), $field['min'], $field['max']);
                break;
            case 'checkbox':
                printf('<input type="checkbox" id="%s" name="%s[%s]" value="1" %s />', $id, $this->option_name, $id, checked('1', $value, false));
                break;
            case 'icons':
                $services = ['youtube' => 'YouTube', 'soundcloud' => 'SoundCloud', 'spotify' => 'Spotify', 'amazon' => 'Amazon Music', 'itunes' => 'Apple Music'];
                echo '<div class="icon-toggle-list">';
                foreach ($services as $key => $label) {
                    $checked = (is_array($value) && in_array($key, $value)) ? 'checked' : '';
                    printf('<label><input type="checkbox" name="%s[show_icons][%s]" value="1" %s /> %s</label>', $this->option_name, $key, $checked, $label);
                }
                echo '</div>';
                break;
        }
        if (!empty($field['desc'])) {
            printf('<p class="description">%s</p>', $field['desc']);
        }
    }
}