<?php
/**
 * Plugin Name: Wetterwarner
 * Plugin URI: https://it93.de/projekte/wetterwarner/
 * Description: Zeigt amtliche Wetterwarnungen in einem Widget an
 * Version: 2.8
 * Author: Tim Knigge
 * Author URI: https://www.linkedin.com/in/tim-knigge-a1238912b/
 * Text Domain: wetterwarner
 * Domain Path: /languages
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */
 
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
if ( ! defined( 'WW_PLUGIN_VER' ) ) {
	define( 'WW_PLUGIN_VER', '2.8' );
}

if ( ! defined( 'WW_SETTINGS_ARGS' ) ) {
    define( 'WW_SETTINGS_ARGS', array(
        'type'              => 'array',
        'sanitize_callback' => 'wetterwarner_sanitize_settings',
        'default'           => array(),
        'show_in_rest'      => false,
    ) );
}

require_once dirname(__FILE__) . '/wetterwarner-settings.php';
require_once dirname(__FILE__) . '/wetterwarner-functions.php';


if(!class_exists('Wetterwarner_Widget')) {
	
    class Wetterwarner_Widget extends WP_Widget {
		public function __construct(){
			parent::__construct(
				'Wetterwarner_Widget',
				'Wetterwarner',
				array(
					'description' => esc_html__('Displays official weather warnings and, if desired, a weather map in a widget.', 'wetterwarner'),
					'customize_selective_refresh' => true,
				)
			);
			add_action( 'wp_enqueue_scripts', 'enqueueStyleAndScripts' );
		}

		/* Update Funktion der Einstellungen in die WP Datenbank */
		public function update($new_instance, $old_instance){
			$instance = array();
			/* Textboxen */
			$instance['title'] = isset($new_instance['title']) ? sanitize_title($new_instance['title'], 'Wetterwarnungen', 'save') : '';
			$instance['ww_widget_titel'] = isset($new_instance['ww_widget_titel']) ? sanitize_text_field($new_instance['ww_widget_titel'], 'Wetterwarnungen', 'save') : '';
			$instance['ww_einleitungstext'] = isset($new_instance['ww_einleitungstext']) ? sanitize_text_field($new_instance['ww_einleitungstext']) : '';
			$instance['ww_hinweistext'] = isset($new_instance['ww_hinweistext']) ? sanitize_text_field($new_instance['ww_hinweistext']) : '';
			$instance['ww_text_feed'] = isset($new_instance['ww_text_feed']) ? sanitize_text_field($new_instance['ww_text_feed']) : '';
			$instance['ww_feed_id'] = isset($new_instance['ww_feed_id']) ? sanitize_key(strtolower($new_instance['ww_feed_id'])) : '';
			$instance['ww_kartengroesse'] = isset($new_instance['ww_kartengroesse']) && is_numeric($new_instance['ww_kartengroesse']) ? (int)$new_instance['ww_kartengroesse'] : (isset($old_instance['ww_kartengroesse']) ? (int)$old_instance['ww_kartengroesse'] : 0);
			$instance['ww_max_meldungen'] = isset($new_instance['ww_max_meldungen']) && is_numeric($new_instance['ww_max_meldungen']) ? (int)$new_instance['ww_max_meldungen'] : (isset($old_instance['ww_max_meldungen']) ? (int)$old_instance['ww_max_meldungen'] : 0);
			
			$map_mapping = wetterwarner_get_map_mapping();

			if (isset($map_mapping[$new_instance['ww_kartenbundesland']])) {
				$mapfilename = $map_mapping[$new_instance['ww_kartenbundesland']];
			} else {
				$mapfilename = "warning_map.webp";
			}
			$widget_id = $this->id;
			$instance['ww_kartenbundeslandURL'] = (string) $mapfilename;
			$instance['ww_kartenbundesland'] = (string) wp_strip_all_tags($new_instance['ww_kartenbundesland']);
			
			/* Checkboxes */
			$fields = [
			'ww_immer_zeigen',
			'ww_feed_zeigen',
			'ww_gueltigkeit_zeigen',
			'ww_quelle_zeigen',
			'ww_tooltip_zeigen',
			'ww_icons_zeigen',
			'ww_hintergrundfarbe',
			'ww_meldungen_verlinken',
			'ww_doppelte_ausblenden',
			];

			foreach ($fields as $field) {
				if (isset($new_instance[$field])) {
					$instance[$field] = $new_instance[$field] ? 1 : 0;
				}
			}
			
			/* Cache leeren und Daten erneut abrufen */
			wetterwarner_cache_refresh();
			if($instance['ww_feed_id'] == 100)
				$feed_url = 'https://api.it93.de/wetterwarner/100.rss';
			else
				$feed_url = 'https://wettwarn.de/rss/' . $instance['ww_feed_id'] . '.rss';
				
			wetterwarner_get_file($feed_url);
			wetterwarner_get_file('https://api.it93.de/wetterwarner/worker/files/' . $mapfilename);
			
			return $instance;
		}
		/* Aufbau Formular Widget Einstellungen / Default Werte	*/
        public function form($instance) {
			try{
				$instance = wp_parse_args((array) $instance, array(
					'ww_widget_titel' => esc_html__('Weather alerts', 'wetterwarner'),
					'ww_text_feed' => esc_html__('Weather alerts %region%', 'wetterwarner'),
					'ww_max_meldungen' => '3',
					'ww_feed_id' => 'HAN',
					'ww_einleitungstext' => esc_html__('Weather alerts for %region%', 'wetterwarner'),
					'ww_hinweistext' => esc_html__('No weather alerts for %region%', 'wetterwarner'),
					'ww_kartengroesse' => '65',
					'ww_kartenbundesland' => 'Niedersachsen',
					'ww_kartenbundeslandURL' => 'warning_map_nib.webp'
				));
				
				
				?>
				<p style="border-bottom: 1px solid #DFDFDF;"><strong><?php echo esc_html__('Widget Title','wetterwarner'); ?></strong></p>
				<p>
					<input id="<?php echo esc_attr($this->get_field_id('ww_widget_titel')); ?>" name="<?php echo esc_attr($this->get_field_name('ww_widget_titel')); ?>" type="text" value="<?php echo esc_attr($instance['ww_widget_titel']); ?>" size="18"/>
				</p>
					<p style="border-bottom: 1px solid #DFDFDF;"><strong>Feed ID</strong></p>
					<input id="<?php echo esc_attr($this->get_field_id('ww_feed_id')); ?>" name="<?php echo esc_attr($this->get_field_name('ww_feed_id')); ?>" type="text" maxlength="3" size="3" value="<?php echo esc_attr($instance['ww_feed_id']); ?>" />
					<br><p><?php echo esc_html__('Get feed ID from https://wettwarn.de/warnregion!','wetterwarner'); ?></p>
				<p style="border-bottom: 1px solid #DFDFDF;"><strong><?php echo esc_html__('Options','wetterwarner'); ?></strong></p>
				<table>
					<tr>
						<td><?php echo esc_html__( 'Introduction text', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_einleitungstext' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_einleitungstext' ) ); ?>"
								type="text"
								value="<?php echo esc_attr( $instance['ww_einleitungstext'] ); ?>"
								size="20"
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Information text', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_hinweistext' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_hinweistext' ) ); ?>"
								type="text"
								value="<?php echo esc_attr( $instance['ww_hinweistext'] ); ?>"
								size="20"
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Show Feed-Link', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_feed_zeigen' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_feed_zeigen' ) ); ?>"
								type="checkbox"
								value="1"
								<?php checked( 1, $instance['ww_feed_zeigen'], true ); ?>
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Feed text', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_text_feed' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_text_feed' ) ); ?>"
								type="text"
								value="<?php echo esc_attr( $instance['ww_text_feed'] ); ?>"
								size="20"
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Max messages', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_max_meldungen' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_max_meldungen' ) ); ?>"
								type="text"
								maxlength="2"
								size="3"
								value="<?php echo esc_attr( $instance['ww_max_meldungen'] ); ?>"
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Size of map', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_kartengroesse' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_kartengroesse' ) ); ?>"
								type="text"
								maxlength="3"
								size="3"
								value="<?php echo esc_attr( $instance['ww_kartengroesse'] ); ?>"
							/>
							<?php echo esc_html__( '0 = map invisible', 'wetterwarner' ); ?>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Federal state of map', 'wetterwarner' ); ?></td>
						<td>
							<select
								id="<?php echo esc_attr( $this->get_field_id( 'ww_kartenbundesland' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_kartenbundesland' ) ); ?>"
							>
								<?php
								$ww_bundeslaender = array(
									'Deutschland', 'Baden-Württemberg', 'Bayern', 'Berlin', 'Brandenburg',
									'Bremen', 'Hamburg', 'Hessen', 'Mecklenburg-Vorpommern', 'Niedersachsen',
									'Nordrhein-Westfalen', 'Rheinland-Pfalz', 'Saarland', 'Sachsen',
									'Sachsen-Anhalt', 'Schleswig-Holstein', 'Thüringen'
								);
								foreach ( $ww_bundeslaender as $land ) {
									printf(
										'<option value="%1$s"%2$s>%1$s</option>',
										esc_attr( $land ),
										selected( $instance['ww_kartenbundesland'], $land, false )
									);
								}
								?>
							</select>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Show validity', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_gueltigkeit_zeigen' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_gueltigkeit_zeigen' ) ); ?>"
								type="checkbox"
								value="1"
								<?php checked( 1, $instance['ww_gueltigkeit_zeigen'], true ); ?>
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Show source', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_quelle_zeigen' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_quelle_zeigen' ) ); ?>"
								type="checkbox"
								value="1"
								<?php checked( 1, $instance['ww_quelle_zeigen'], true ); ?>
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Show always', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_immer_zeigen' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_immer_zeigen' ) ); ?>"
								type="checkbox"
								value="1"
								<?php checked( 1, $instance['ww_immer_zeigen'], true ); ?>
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Create tooltip', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_tooltip_zeigen' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_tooltip_zeigen' ) ); ?>"
								type="checkbox"
								value="1"
								<?php checked( 1, $instance['ww_tooltip_zeigen'], true ); ?>
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Show Icons', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_icons_zeigen' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_icons_zeigen' ) ); ?>"
								type="checkbox"
								value="1"
								<?php checked( 1, $instance['ww_icons_zeigen'], true ); ?>
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Show background color', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_hintergrundfarbe' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_hintergrundfarbe' ) ); ?>"
								type="checkbox"
								value="1"
								<?php checked( 1, $instance['ww_hintergrundfarbe'], true ); ?>
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Link messages', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_meldungen_verlinken' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_meldungen_verlinken' ) ); ?>"
								type="checkbox"
								value="1"
								<?php checked( 1, $instance['ww_meldungen_verlinken'], true ); ?>
							/>
						</td>
					</tr>
					<tr>
						<td><?php echo esc_html__( 'Hide duplicates', 'wetterwarner' ); ?></td>
						<td>
							<input
								id="<?php echo esc_attr( $this->get_field_id( 'ww_doppelte_ausblenden' ) ); ?>"
								name="<?php echo esc_attr( $this->get_field_name( 'ww_doppelte_ausblenden' ) ); ?>"
								type="checkbox"
								value="1"
								<?php checked( 1, $instance['ww_doppelte_ausblenden'], true ); ?>
							/>
						</td>
					</tr>
				</table>

				<p style="border-bottom: 1px solid #DFDFDF;"></p>
				<?php 
			}
			catch( Exception $e ) {
				echo '<p style="color:red; font-weight:bold">' . esc_html__('Sorry, something went wrong.', 'wetterwarner') .'</p>',  esc_html($e->getMessage()), "\n";
				echo '<br><br>';
			}
        }
			public function widget( $args, $instance ) {
				try {
					$options  = get_option( 'wetterwarner_settings', array() );
					$feed_rss = plugin_dir_url( __FILE__ ) . 'tmp/' . esc_attr( $instance['ww_feed_id'] ) . '.rss';
					$xml_data = wetterwarner_xml( $feed_rss );
					$feed     = wetterwarner_meldungen( $xml_data, $instance );
					$param    = wetterwarner_parameter( $xml_data, $instance );

					// Widget-Wrapper öffnen
					echo wp_kses_post( $args['before_widget'] );

					// Nur anzeigen, wenn es Warnungen gibt ODER „immer zeigen“ aktiv ist
					$has_warnings = ! empty( $feed[0]['title'] ) && $feed[0]['title'] !== 'Keine Warnungen';
					if ( $has_warnings || ! empty( $instance['ww_immer_zeigen'] ) ) {

						// Titel ausgeben
						echo wp_kses_post( $args['before_title']
						   . $param->widget_title 
						   . $args['after_title']);

						if($has_warnings){
							// Einleitungstext
							if ( ! empty( $param->einleitung ) ) {
								echo '<span class="ww_einleitung">'
								   . wp_kses_post( $param->einleitung )
								   . '</span><br>';
							}
					
							// Liste starten
							echo '<ul class="ww_wetterwarnungen">';

							$count = absint( $instance['ww_max_meldungen'] );
							$seen  = array();
							$tooltips = array();

							foreach ( $feed as $item ) {
								if ( $count-- <= 0 ) {
									break;
								}

								// Kurz-Titel extrahieren
								$title_raw    = $item['title'];
								$has_prefix   = strpos( $title_raw, 'VORABINFORMATION' ) !== false;
								$shorttitle   = $has_prefix
									? trim( explode( 'VORABINFORMATION', $title_raw, 2 )[1] )
									: trim( explode( ':', $title_raw, 2 )[1] );
								$tooltip_data = trim( preg_replace( '/\s+/', ' ',
									explode( 'Quelle:', $item['description'], 2 )[0]
								) );

								// Doppelte verwalten
								if ( in_array( $shorttitle, $seen, true ) && ! empty( $instance['ww_doppelte_ausblenden'] ) ) {
									// hier Tooltip nur ergänzen
									$tooltips[ $shorttitle ] .= '<br>— ' . esc_html( $tooltip_data );
									$count++;
									continue;
								}

								$seen[]        = $shorttitle;
								$tooltips[ $shorttitle ] = esc_html( $tooltip_data );

								// List-Item öffnen
								$style_attr = '';
								if ( ! empty( $instance['ww_hintergrundfarbe'] ) ) {
									$style_attr = ' style="' . esc_attr( wetterwarner_meldung_hintergrund( $item, $options ) ) . '"';
								}
								echo '<li class="ww_wetterwarnung"' . esc_attr($style_attr) . '>';

								// Link
								$tooltip_markup = '';
								if ( ! empty( $instance['ww_tooltip_zeigen'] ) ) {
									// liefert z.B. onmouseover="popup('...')"
									$tooltip_markup = ' ' . wetterwarner_tooltip( $tooltips[ $shorttitle ] );
								}

								// Wenn verlinken gewünscht
								if ( ! empty( $instance['ww_meldungen_verlinken'] ) ) {
									printf(
										'<a href="%1$s" target="_blank"%2$s>',
										esc_url( $item['link'] ),
										// hier wird das onmouseover-Attribut sicher durch wp_kses gelassen
										wp_kses( $tooltip_markup, array( 'a' => array( 'onmouseover' => true ) ) )
									);
								} elseif ( $tooltip_markup ) {
									printf(
										'<a%1$s>',
										wp_kses( $tooltip_markup, array( 'a' => array( 'onmouseover' => true ) ) )
									);
								}

								// Icon
								if ( ! empty( $instance['ww_icons_zeigen'] ) ) {
									echo '<i class="' . esc_attr( wetterwarner_icons( $shorttitle ) ) . '"></i> ';
								}

								// Titel
								echo esc_html( $shorttitle );

								// Link-Ende
								if ( ! empty( $instance['ww_meldungen_verlinken'] ) || $tooltip_attr ) {
									echo '</a>';
								}

								// Vorabinformation
								if ( $has_prefix ) {
									echo '<br><span class="ww_Info"><i class="fa fa-info"></i> '
									   . esc_html__( 'prior information', 'wetterwarner' )
									   . '</span>';
								}

								// Gültigkeit & Quelle
								if ( ! empty( $instance['ww_gueltigkeit_zeigen'] ) ) {
									echo wp_kses_post( wetterwarner_gueltigkeit( $item, $param ) );
								}
								if ( ! empty( $instance['ww_quelle_zeigen'] ) ) {
									echo wp_kses_post( wetterwarner_quelle( $item ) );
								}

								echo '</li>';
							} // Ende foreach

							echo '</ul>'; // Liste schließen
						}
						else
							echo wp_kses_post($param->hinweistext) . "</br>";
						
						// Wetterkarte
						if ( absint( $instance['ww_kartengroesse'] ) > 0 ) {
							echo wp_kses_post( wetterwarner_wetterkarte( $instance, $args, $param->region ) );
						}

						// RSS-Feed-Link
						if ( ! empty( $instance['ww_feed_zeigen'] ) ) {
							echo wp_kses_post( wetterwarner_feed_link( $instance, $param ) );
						}
					}
					echo wp_kses_post( $args['after_widget']);
				}
				catch ( Exception $e ) {
					// Fallback-Ausgabe bei Fehler
					echo wp_kses_post($args['before_widget'])
					   . wp_kses_post($args['before_title'])
					   . esc_html__( 'Wetterwarner', 'wetterwarner' )
					   . wp_kses_post($args['after_title'])
					   . '<p style="color:red;font-weight:bold;">'
					   . esc_html__( 'Sorry, something went wrong.', 'wetterwarner' )
					   . '</p>'
					   . '<p>' . esc_html( $e->getMessage() ) . '</p>'
					   . wp_kses_post($args['after_widget']);
				}
			}

		}
    }
	/* Widget  registrieren*/
	add_action('widgets_init', 'wetterwarner_init_widget');
	add_action('plugin_action_links_' . plugin_basename( __FILE__ ), 'wetterwarner_action_links' );
	add_action('plugins_loaded', 'wetterwarner_load_textdomain');
	add_action('upgrader_process_complete', 'wetterwarner_upgrade_completed', 10, 2);
	add_action('wetterwarner_data_update', 'wetterwarner_data_update');
	add_filter('debug_information', 'wetterwarner_debug_info' );
	add_filter('site_status_tests', 'wetterwarner_add_konfig_check' );
	add_filter('cron_schedules', 'wetterwarner_cron_schedule');
	register_activation_hook(__FILE__, 'wetterwarner_activation');
	register_deactivation_hook(__FILE__, 'wetterwarner_deactivation');
	
	
?>