<?php

defined( 'ABSPATH' ) || exit; // Exit if accessed directly


if( ! class_exists( 'KANEWS_WEATHER' ) ) {

	class KANEWS_WEATHER {

    private $defaults = [
      'city' => 'istanbul',
      'units' => 'metric',
      'lang' => 'tr',
      'show_wind' => true,
      'show_humidity' => true,
      'show_pressure' => true,
      'show_min_temp' => true,
      'show_max_temp' => true,
      'show_forecast' => false,
      'forecast_days' => 6,
      'show_full_link' => true,
      'cache_time' => 3600, // 1 hour
      'title' => '',
      'show_dropdown' => true,
    ];

    public $atts;
		public $api_key;
		public $location;
		public $city_slug;
		public $units;
		public $transient_name;
		public $lang;

    private $weather_backgrounds = [
      'thunderstorm' => [
        'color' => 'linear-gradient(rgb(44, 70, 108) 0%, rgb(20, 36, 60) 100%)',
        'image' => '/assets/img/static/weather/Thunderstorm.webp',
        'range' => [200, 299]
      ],
      'drizzle' => [
        'color' => 'linear-gradient(rgb(44, 70, 108) 0%, rgb(20, 36, 60) 100%)',
        'image' => '/assets/img/static/weather/Rain.webp',
        'range' => [300, 499]
      ],
      'rain' => [
        'color' => 'linear-gradient(rgb(52, 92, 132) 0%, rgb(44, 76, 116) 100%)',
        'image' => '/assets/img/static/weather/Rain-1.webp',
        'range' => [500, 599]
      ],
      'snow' => [
        'color' => 'linear-gradient(rgb(41, 87, 147) 0%, rgb(12, 60, 124) 100%)',
        'image' => '/assets/img/static/weather/Snow.webp',
        'range' => [600, 699]
      ],
      'mist' => [
        'color' => 'linear-gradient(rgb(45, 65, 86) 0%, rgb(26, 28, 36) 100%)',
        'image' => '/assets/img/static/weather/Hazy.webp',
        'range' => [700, 799]
      ],
      'clear' => [
        'color' => 'linear-gradient(rgb(36, 84, 148) 0%, rgb(28, 68, 132) 100%)',
        'image' => '/assets/img/static/weather/Sunny.webp',
        'range' => [800, 800]
      ],
      'clouds' => [
        'color' => 'linear-gradient(rgb(76, 92, 122) 0%, rgb(52, 68, 100) 100%)',
        'image' => '/assets/img/static/weather/Cloudy-2.webp',
        'range' => [801, 899]
      ]
    ];

    // Setup
    function __construct($options = []) {
      $this->atts = wp_parse_args($options, $this->defaults);
      $this->api_key        = kanews_get_option('openweathermap-api');
      $this->units          = apply_filters( 'Kanews/Widget/Weather/units', 'metric' );
      $this->lang           = apply_filters( 'Kanews/Widget/Weather/lang', 'tr' );
      $this->location       = isset($options['city']) ? replace_tr(sanitize_text_field($options['city'])) : 'istanbul';
      $this->city_slug      = is_numeric($this->location) ? $this->location : sanitize_title($this->location);
      $this->transient_name = 'kanews_weather_widget_' . $this->city_slug;

      // Şehir değiştiğinde önbelleği temizle
      $this->maybe_clear_cache();
      
      // Output
			$this->show();
    }

    // Önbellek temizleme için yeni bir metod ekleyelim
    private function maybe_clear_cache() {
      $current_city = $this->city_slug;
      $cached_city = get_transient('kanews_last_weather_city_' . $this->atts['widget_id']);

      if ($cached_city !== $current_city) {
        self::clear_cache($cached_city);
        set_transient('kanews_last_weather_city_' . $this->atts['widget_id'], $current_city, DAY_IN_SECONDS);
      }
    }

    private function get_background($weather_id) {
      foreach ($this->weather_backgrounds as $type => $data) {
        if ($weather_id >= $data['range'][0] && $weather_id <= $data['range'][1]) {
          return [
            'color' => $data['color'],
            'image' => get_template_directory_uri() . $data['image']
          ];
        }
      }
      return $this->weather_backgrounds['clear'];
    }

    private function render_meta_item($label, $value, $icon = '', $unit = '') {
      if (!$this->atts["show_$label"]) return '';
      
      // Türkçe etiket karşılıklarını tanımlayalım
      $labels = [
        'wind' => esc_html__('Rüzgar Hızı', 'kanews'),
        'humidity' => esc_html__('Nem', 'kanews'),
        'pressure' => esc_html__('Basınç', 'kanews'),
        'min_temp' => esc_html__('Minimum Sıcaklık', 'kanews'),
        'max_temp' => esc_html__('Maksimum Sıcaklık', 'kanews')
      ];

      // Etiketin Türkçe karşılığını alalım
      $label_text = isset($labels[$label]) ? $labels[$label] : $label;
      
      return sprintf(
        '<div class="weather-widget__meta-item">
          <div class="weather-widget__meta-label">%s %s</div>
          <div class="weather-widget__meta-value">%s%s</div>
        </div>',
        $icon,
        $label_text,
        $value,
        $unit
      );
    }

    private function show(){
      $data = $this->get_weather();
      $data = $data['now'];

			if(  isset($data['message']) && !empty($data['message']) ) {
      echo $data['message']; return;
      }

      if( ! is_array( $data ) || !isset($data['weather'])  )
      return;

      $weather_id = ! empty( $data['weather'][0]['id'] ) ? $data['weather'][0]['id']  : 800;

      // Add fallback for mb_strtolower
      if (!function_exists('mb_strtolower')) {
          function mb_strtolower($str) {
              return strtolower($str);
          }
      }

      ?>

      <div class="weather-widget">
        <div class="weather-widget__bg"></div>
        <div class="weather-widget__container">
          <div class="weather-widget__header">
            <h2 class="weather-widget__header-title" <?php echo $this->atts['show_dropdown'] ? 'data-toggle="select-weather-city"' : ''; ?>>
              <?php 
              if (!empty($this->atts['title'])) {
                  echo esc_html($this->atts['title']);
              } else {
                  echo sprintf(esc_html__('%s için Hava Durumu', 'kanews'), $this->atts['city']);
              }
              ?>
              <?php if ($this->atts['show_dropdown']): ?>
                  <i class="icon-arrow icon-180deg"></i>
              <?php endif; ?>
              <span class="weather-widget__info-icon" 
                    role="tooltip" 
                    data-microtip-position="bottom" 
                    aria-label="<?php 
                      // Hava durumu açıklamasını oluştur
                      $weather_info = sprintf(
                          '%s şehrinde şu anda hava %s. Sıcaklık %s°C ve hissedilen sıcaklık %s°C. ',
                          $this->atts['city'],
                          mb_strtolower($data['weather'][0]['description']),
                          round($data['main']['temp'], 1),
                          round($data['main']['feels_like'], 1)
                      );


                      echo esc_attr($weather_info);
                    ?>">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <circle cx="12" cy="12" r="10"></circle>
                      <path d="M12 16v-4"></path>
                      <path d="M12 8h.01"></path>
                  </svg>
              </span>
            </h2>
            <?php if ($this->atts['show_dropdown']): ?>
                <div id="select-weather-city" class="kanews-waether-cities kanews-scroll d-flex flex-wrap">
                    <input placeholder="<?php esc_attr_e('Şehir ara', 'kanews'); ?>" id="kanews-weather-search2">
                    <?php foreach(kanews_get_turkey_cities2() as $select_key => $select_city) { ?>
                        <a class="kanews-weather-city kanews-weather-city2" 
                           href="<?php echo kanews_get_page_link('sehir', strtolower(replace_tr($select_city)), 'weather'); ?>" 
                           data-city="<?php echo $select_city; ?>">
                            <?php echo $select_city; ?>
                        </a>
                    <?php } ?>
                </div>
            <?php endif; ?>
            <div class="weather-widget__header-time"><?php echo date('H:i'); ?></div>
          </div>

          <div class="weather-widget__content">
            <div class="weather-widget__content-icon">
              <?php echo kanews_get_local_image(KAN_TEMPLATE_URL.'/assets/img/weather/svg/'.$data['weather'][0]['icon'].'.svg', $attr = ['width' => 128, 'height' => 128, 'alt' => $data['weather'][0]['description'] ] ); ?>
            </div>
            <div>
              <div class="weather-widget__content-temp">
                <?php echo round($data['main']['temp'], 1); ?><sup>°C</sup>
              </div>
              <div class="weather-widget__content-info">
                <div><?php echo ucwords($data['weather'][0]['description']); ?></div>
                <div><?php 
                  echo sprintf(
                    esc_html__('Hissedilen %s°', 'kanews'),
                    round($data['main']['feels_like'], 1)
                  ); 
                ?></div>
              </div>
            </div>
          </div>

          <div class="weather-widget__meta">
            <?php
            echo $this->render_meta_item('wind', round($data['wind']['speed'], 1), '<svg aria-label="'.esc_html__('Rüzgar Hızı', 'kanews').'" width="18" height="18" aria-hidden="false" role="img" viewBox="0 0 24 24"><path d="M6 8.67h5.354c1.457 0 2.234-1.158 2.234-2.222S12.687 4.4 11.354 4.4c-.564 0-1.023.208-1.366.488M3 11.67h15.54c1.457 0 2.235-1.158 2.235-2.222S19.873 7.4 18.54 7.4c-.747 0-1.311.365-1.663.78M6 15.4h9.389c1.457 0 2.234 1.159 2.234 2.223 0 1.064-.901 2.048-2.234 2.048a2.153 2.153 0 0 1-1.63-.742" stroke-width="2" stroke="currentColor" stroke-linecap="round" fill="none"></path></svg>', 'mph/s');
            echo $this->render_meta_item('humidity', round($data['main']['humidity']), '<svg aria-label="'.esc_html__('Nem', 'kanews').'" fill="currentColor" aria-hidden="false" enable-background="new 0 0 510.013 510.013" height="18" viewBox="0 0 510.013 510.013" width="18" xmlns="http://www.w3.org/2000/svg"><g><path d="m179.207 446c-26.473 0-47.2-21.354-47.2-47 0-20.68 13.41-38.27 32-44.55v-52.45h-33v-30h33v-34h-33v-30h33v-34h-33v-30h33v-73h30v222.14c26.941-52.674 66.638-108.692 104-156.58v-17.56c0-65.77-53.215-119-119-119-65.62 0-119 53.38-119 119v391h170.79c-22.39-16.3-40.32-38.37-51.59-64z"/><path d="m323.007 153.29c-38.46 49.295-128.75 170.151-126.96 232.86 0 47.318 32.114 97.368 82.72 115.9 10.498 4.155 28.195 7.7 36.24 7.7 72.982 4.68 135-53.608 135-126.75 0-61.183-89.706-181.909-127-229.71zm47.5 268.71c-8 0-14.5-6.5-14.5-14.5s6.5-14.5 14.5-14.5 14.5 6.5 14.5 14.5-6.5 14.5-14.5 14.5zm-88-101c10.053 0 17.047 10.004 13.63 19.46v.01c-2.04 5.55-7.37 9.53-13.63 9.53-8 0-14.5-6.5-14.5-14.5s6.5-14.5 14.5-14.5zm28.71 109.11c-5.692-3.065-1.13-.609-26.42-14.22 21.799-40.488 10.782-20.028 56-104l26.42 14.22z"/></g></svg>', '%');
            echo $this->render_meta_item('pressure', $data['main']['pressure'], '<svg aria-label="'.esc_html__('Basınç', 'kanews').'" aria-hidden="false" width="18" height="18" viewBox="0 0 24 24"><path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm0 18a8 8 0 1 1 8-8 8 8 0 0 1-8 8zm-4-8a4 4 0 0 1 4-4v8a4 4 0 0 1-4-4z" fill="currentColor"/></svg>', 'mb');
            echo $this->render_meta_item('min_temp', $data['main']['temp_min'], '<svg aria-label="'.esc_html__('Minimum Sıcaklık', 'kanews').'" width="18" height="18" aria-hidden="false" viewBox="0 0 24 24"><path d="M15 13V5a3 3 0 0 0-6 0v8a5 5 0 1 0 6 0zm-3 4a2 2 0 1 1 2-2 2 2 0 0 1-2 2z" fill="currentColor"/></svg>', '°');
            echo $this->render_meta_item('max_temp', $data['main']['temp_max'], '<svg aria-label="'.esc_html__('Maksimum Sıcaklık', 'kanews').'" width="18" height="18" aria-hidden="false" viewBox="0 0 24 24"><path d="M15 13V5a3 3 0 0 0-6 0v8a5 5 0 1 0 6 0zm-3 4a2 2 0 1 1 2-2 2 2 0 0 1-2 2z" fill="currentColor"/></svg>', '°');
            ?>
          </div>
          <?php if($this->atts['show_full_link'] && kanews_get_option('weather-page') != ''): ?>
        <a class="kanews-kmg21" href="<?php echo kanews_get_page_link('sehir', strtolower(replace_tr($this->atts['city'])), 'weather'); ?>" >
          <?php esc_html_e('Daha Fazla Detay', 'kanews'); ?>
        </a>
      <?php endif; ?>
        </div>
      </div>
      <?php 
      

      // Tahmin widget'ını göster
      if ($this->atts['show_forecast']) {
          $this->show_forecast();
      }
    }

    // Connect Weather Api
    private function weather_api($type = 'weather'){
      
      $query = is_numeric( $this->location ) ? array( 'id' => $this->location ) : array( 'q' =>  strtolower(str_replace("-", "+", $this->location))  );
			$query['lang']  = $this->lang ;
			$query['units'] = $this->units;
			$query['appid'] = $this->api_key;

			$api_url = add_query_arg( $query, 'http://api.openweathermap.org/data/2.5/'.$type );

			$api = wp_remote_get( $api_url, array( 'timeout' => 10 ) );

			if( is_wp_error( $api ) )
      return array( 'error' => $api->get_error_message() );

			$weather_data = json_decode( $api['body'], true );

			if( isset( $weather_data->cod ) && $weather_data->cod != 200 )
      return array( 'error' => $weather_data->message );

			return $weather_data;

    }

    // Set Transient
    private function get_weather(){

      if( ! $weather_data = get_transient( $this->transient_name ) ){

				$weather_data = array(
					'now'      => $this->weather_api('weather')
				);

				foreach ( $weather_data as $key => $value ){
					if( is_array( $value ) && ! empty( $value['error'] ) ){
						break;
					}
				}

				if( $weather_data['now'] ){
					set_transient( $this->transient_name, $weather_data, $this->atts['cache_time'] );
				}
			}

			return $weather_data;

		}

    // Clear Cache
    public static function clear_cache($location = false) {
      if (!$location) {
        return;
      }

      global $wpdb;
      
      // Hem normal hem de forecast önbelleğini temizle
      $wpdb->query($wpdb->prepare(
        "DELETE FROM {$wpdb->options} 
        WHERE option_name LIKE %s 
        OR option_name LIKE %s",
        '_transient_kanews_weather_' . $location . '%',
        '_transient_timeout_kanews_weather_' . $location . '%'
      ));
    }
    
    // Clear Expired
    public static function clear_expired_weather() {

      // Run this twice daily
      if( get_transient( 'kan_check_weather_daily' ) ){
        return;
      }

      global $wpdb;

      // get current PHP time, offset by a minute to avoid clashes with other tasks
      $threshold = time() - MINUTE_IN_SECONDS;

      // delete expired transients, using the paired timeout record to find them
      $sql = "
        delete from t1, t2
        using {$wpdb->options} t1
        join {$wpdb->options} t2 on t2.option_name = replace(t1.option_name, '_timeout', '')
        where (t1.option_name like '\_transient\_timeout\_kanews_weather_%' or t1.option_name like '\_site\_transient\_timeout\_kanews_weather_%')
        and t1.option_value < '$threshold'
      ";
      $wpdb->query($sql);

      // delete orphaned transient expirations
      $sql = "
        delete from {$wpdb->options}
        where (
              option_name like '\_transient\_timeout\_kanews_weather_%'
          or option_name like '\_site\_transient\_timeout\_kanews_weather_%'
        )
        and option_value < '$threshold'
      ";
      $wpdb->query($sql);

      // Run this twice daily
      set_transient( 'kan_check_weather_daily', true, 12 * HOUR_IN_SECONDS );
    }

    // Hava tahminini getir
    public function get_forecast() {
        if (!$weather_data = get_transient($this->transient_name . '_forecast')) {
            $weather_data = $this->weather_api('forecast');
            
            if ($weather_data && !isset($weather_data['error'])) {
                set_transient(
                    $this->transient_name . '_forecast', 
                    $weather_data, 
                    $this->atts['cache_time']
                );
            }
        }
        return $weather_data;
    }

    // Tahmin verilerini formatla
    private function format_forecast_data($data) {
        $forecast_days = [];
        $today_date = date('Ymd', current_time('timestamp', 0));
        
        foreach ((array)$data['list'] as $forecast) {
            $day_of_week = date('Ymd', $forecast['dt']);
            
            if ($today_date > $day_of_week) continue;
            
            if (empty($forecast_days[$day_of_week])) {
                $forecast_days[$day_of_week] = [
                    'utc' => $forecast['dt'],
                    'icon' => $forecast['weather'][0]['icon'],
                    'description' => $forecast['weather'][0]['description'],
                    'temp' => !empty($forecast['main']['temp_max']) ? 
                             round($forecast['main']['temp_max']) : '',
                    'temp_min' => round($forecast['main']['temp_min']),
                    'temp_max' => round($forecast['main']['temp_max']),
                    'humidity' => round($forecast['main']['humidity']),
                    'wind_speed' => round($forecast['wind']['speed'], 1)
                ];
            } else {
                if ($forecast['main']['temp_max'] > $forecast_days[$day_of_week]['temp']) {
                    $forecast_days[$day_of_week]['temp'] = round($forecast['main']['temp_max']);
                    $forecast_days[$day_of_week]['icon'] = $forecast['weather'][0]['icon'];
                }
                if ($forecast['main']['temp_min'] < $forecast_days[$day_of_week]['temp_min']) {
                    $forecast_days[$day_of_week]['temp_min'] = round($forecast['main']['temp_min']);
                }
            }
        }

        return array_slice($forecast_days, 0, $this->atts['forecast_days']);
    }

    // Tahmin widget'ını göster
    public function show_forecast() {
        $forecast_data = $this->get_forecast();
        if (!$forecast_data || isset($forecast_data['error'])) return;

        $forecast_days = $this->format_forecast_data($forecast_data);
        
        if (empty($forecast_days)) return;

        ?>
        <div class="weather-widget__forecast">
            <?php foreach ($forecast_days as $day): ?>
                <div class="weather-widget__forecast-day">
                    <div class="weather-widget__forecast-date">
                        <?php echo date_i18n('l', $day['utc']); ?>
                    </div>
                    <div class="weather-widget__forecast-icon">
                        <?php echo kanews_get_local_image(
                            KAN_TEMPLATE_URL.'/assets/img/weather/svg/'.$day['icon'].'.svg',
                            ['width' => 48, 'height' => 48, 'alt' => $day['description']]
                        ); ?>
                    </div>
                    <div class="weather-widget__forecast-temp">
                        <span class="max"><?php echo $day['temp_max']; ?>°</span>
                        <span class="min"><?php echo $day['temp_min']; ?>°</span>
                    </div>
                    <?php if ($this->atts['show_wind']): ?>
                        <div class="weather-widget__forecast-wind">
                            <?php echo $day['wind_speed']; ?> mph/s
                        </div>
                    <?php endif; ?>
                    <?php if ($this->atts['show_humidity']): ?>
                        <div class="weather-widget__forecast-humidity">
                            <?php echo $day['humidity']; ?>%
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
        <?php
    }

    // Saatlik tahmin için yeni bir public metod ekleyelim
    public function get_hourly_forecast() {
        $forecast_data = $this->get_forecast();
        if (!$forecast_data || isset($forecast_data['error'])) {
            return [];
        }

        $forecast_days = [];
        $today_date = date('Ymd', current_time('timestamp', 0));
        
        foreach ((array)$forecast_data['list'] as $forecast) {
            $day = date('d.m.Y', $forecast['dt']);
            $hour = date('H:i', $forecast['dt']);
            
            if (!isset($forecast_days[$day])) {
                $forecast_days[$day] = [];
            }
            
            $forecast_days[$day][$hour] = [
                'temp' => round($forecast['main']['temp'], 1),
                'icon' => $forecast['weather'][0]['icon'],
                'description' => $forecast['weather'][0]['description'],
                'humidity' => round($forecast['main']['humidity']),
                'wind_speed' => round($forecast['wind']['speed'], 1)
            ];
        }

        return $forecast_days;
    }

    // Saatlik tahmin gösterimi için yeni bir metod
    public function show_hourly_forecast($slick_options = []) {
        $forecast_days = $this->get_hourly_forecast();
        if (empty($forecast_days)) return;

        foreach ($forecast_days as $day => $hours) {
            $nameOfDay = date('D', strtotime($day));
            $dayName = kanews_translate_days($nameOfDay);
            ?>
            <h3><?php echo $day . ' ' . $dayName . ' ' . esc_html__('Günü Hava Durumu', 'kanews'); ?></h3>
            <div class="kanews-slider-wrapper kanews-simplebox-wrapper mb-2" data-slick='<?php echo wp_json_encode($slick_options); ?>'>
                <?php foreach ($hours as $hour => $data) { ?>
                    <div class="kanews-simple-box">
                        <div class="kanews-simple-box-label"><?php echo $hour; ?></div>
                        <div class="kanews-simple-box-icon">
                            <?php echo kanews_get_local_image(
                                KAN_TEMPLATE_URL.'/assets/img/weather/svg/'.$data['icon'].'.svg',
                                ['width' => 48, 'height' => 48, 'alt' => $data['description']],
                                '1e1'
                            ); ?>
                        </div>
                        <div class="kanews-simple-box-value"><?php echo $data['temp']; ?>°</div>
                    </div>
                <?php } ?>
            </div>
            <?php
        }
    }

  }
}

add_action( 'admin_head', 'KANEWS_WEATHER::clear_expired_weather' );