<?php

if ( ! defined( 'ABSPATH' ) ) {
	die();
}

if(is_admin() || is_customize_preview(  )) {
	require_once dirname(__FILE__) . '/widget-framework.php';
}

// Widget Class
class kanews_widget_class_game_center extends WP_Widget {
	private $instance;

  // Create
	public function __construct(){
		parent::__construct(
			'kanews_widget_game_center',
			KAN_THEME_NAME . ' - ' . __("Maç Merkezi", 'kanews'),
			['classname' => 'kanews_widget_game_center']
		);
		$this->instance = [];
	}
  
  // Front-end
	public function widget($args, $instance)
	{
		$this->instance = $instance; // instance'ı sınıf değişkenine ata
		
    // Görünürlük kontrolü
    $hide_mobile = isset($instance['hide_mobile']) && $instance['hide_mobile'] === 'on';
    $hide_desktop = isset($instance['hide_desktop']) && $instance['hide_desktop'] === 'on';

    if (($hide_mobile && kan_is_mobile()) || ($hide_desktop && !kan_is_mobile())) {
			return;
		}

    // Instance değerlerini al
    $title = apply_filters('widget_title', $instance['title'] ?? '');
    $type = $instance['type'] ?? 'table';
    $leagues = $instance['game_center'] ?? $this->get_default_leagues();
    $pages = $instance['pages'] ?? '';
    $bg_color = !empty($instance['bg-color']) ? 'background: ' . $instance['bg-color'] : '';

    // Gösterim sayısını belirle
    $show = $this->get_show_count($args['id'] ?? '');

    // Maç verilerini al
    date_default_timezone_set('Europe/Istanbul');
    $date = date('Y-m-d');    
    $cons_matches = json_decode(kanews_live_score_data($date, $leagues), true);

    // Widget görünümünü oluştur
    $this->render_widget_content($type, $title, $show, $cons_matches, $pages, $bg_color);
	}
  
  // Update Form
	public function update($new_instance, $old_instance)
	{
		$instance = $old_instance;

		$instance['title'] = strip_tags($new_instance['title']);
		$instance['pages'] = $new_instance['pages'];
		$instance['type'] = $new_instance['type'];
		$instance['game_center'] = (array)$new_instance['game_center'];
    $instance['hide_desktop'] = $new_instance['hide_desktop'];
		$instance['hide_mobile'] = $new_instance['hide_mobile'];
		
		return $instance;
	}

  // Back-end form
	public function form($instance)
	{
		$defaults = [
			'title' => __('Maç Merkezi', 'kanews'),
			'type' => 'table', 
      'pages' => 'all', 
			'game_center' => [],
			'hide_desktop' => 'off',
			'hide_mobile' => 'off'
		];
		$instance = wp_parse_args((array) $instance, $defaults);

    // Genel Ayarlar
    Kanews_Form_Elements::render_accordion_field([
        'title' => __('Genel Ayarlar', 'kanews'),
        'content' => [
            [
                'type' => Kanews_Form_Elements::TYPE_TEXT,
                'id' => $this->get_field_id('title'),
                'name' => $this->get_field_name('title'),
                'label' => __('Başlık', 'kanews'),
                'value' => $instance['title']
            ],
            [
                'type' => Kanews_Form_Elements::TYPE_SELECT,
                'id' => $this->get_field_id('type'),
                'name' => $this->get_field_name('type'),
                'label' => __('Tür', 'kanews'),
                'value' => $instance['type'],
                'options' => [
                    'table' => __('Tablo', 'kanews'),
                    'ticker' => __('Ticker', 'kanews')
                ]
            ],
            [
                'type' => Kanews_Form_Elements::TYPE_SELECT,
                'id' => $this->get_field_id('pages'),
                'name' => $this->get_field_name('pages'),
                'label' => __('Sayfa', 'kanews'),
                'value' => $instance['pages'],
                'options' => Kanews_Form_Elements::get_pages_options()
            ]
        ]
    ]);

    // Lig Ayarları
    Kanews_Form_Elements::render_accordion_field([
        'title' => __('Lig Ayarları', 'kanews'),
        'content' => [
          [
            'type' => Kanews_Form_Elements::TYPE_SELECT2,
            'id' => $this->get_field_id('game_center'),
            'name' => $this->get_field_name('game_center'),
            'label' => __('Gösterilecek Ligler', 'kanews'),
            'value' => (array)$instance['game_center'],
            'multiple' => true,
            'placeholder' => __('Ligleri seçin...', 'kanews'),
             'options' => $this->get_league_options()
          ]
        ]
    ]);

    // Görünürlük Ayarları
    Kanews_Form_Elements::render_accordion_field([
        'title' => __('Görünürlük Ayarları', 'kanews'),
        'content' => [
            [
                'type' => Kanews_Form_Elements::TYPE_TOGGLE,
                'id' => $this->get_field_id('hide_desktop'),
                'name' => $this->get_field_name('hide_desktop'),
                'label' => __('Masaüstünde Gizle', 'kanews'),
                'value' => $instance['hide_desktop']
            ],
            [
                'type' => Kanews_Form_Elements::TYPE_TOGGLE,
                'id' => $this->get_field_id('hide_mobile'),
                'name' => $this->get_field_name('hide_mobile'),
                'label' => __('Mobilde Gizle', 'kanews'),
                'value' => $instance['hide_mobile']
            ]
        ]
    ]);
	}

  // Lig seçeneklerini döndüren yardımcı metod
  private function get_league_options() {
    return [
      '482ofyysbdbeoxauk19yg7tdt' => __('Süper Lig', 'kanews'),
      '2o9svokc5s7diish3ycrzk7jm' => __('1. Lig', 'kanews'),
      '7af85xa75vozt2l4hzi6ryts7' => __('Türkiye Kupası', 'kanews'),
      '4oogyu6o156iphvdvphwpck10' => __('Şampiyonlar Ligi', 'kanews'),
      '4c1nfi2j1m731hcay25fcgndq' => __('Avrupa Ligi', 'kanews'),
      'c7b8o53flg36wbuevfzy3lb10' => __('Konferans Ligi', 'kanews'),
      '2kwbbcootiqqgmrzs6o5inle5' => __('Premier Lig', 'kanews'),
      '6by3h89i2eykc341oz7lv1ddd' => __('Bundesliga', 'kanews'),
      '34pl8szyvrbwcmfkuocjm3r6t' => __('La Liga', 'kanews'),
      '1r097lpxe0xn03ihb7wi98kao' => __('Serie A', 'kanews')
    ];
  }

  private function get_default_leagues() {
    return [
      '482ofyysbdbeoxauk19yg7tdt', // TR Süper Lig
      '2o9svokc5s7diish3ycrzk7jm', // 1. Lig
      '7af85xa75vozt2l4hzi6ryts7', // TR Kupası
      '4oogyu6o156iphvdvphwpck10', // Şampiyonlar Ligi
      '4c1nfi2j1m731hcay25fcgndq', // Avrupa Ligi
      'c7b8o53flg36wbuevfzy3lb10', // Konferans Ligi
      '2kwbbcootiqqgmrzs6o5inle5', // Premier Lig
      '6by3h89i2eykc341oz7lv1ddd', // Bundesliga
      '34pl8szyvrbwcmfkuocjm3r6t', // La Liga
      '1r097lpxe0xn03ihb7wi98kao'  // Serie A
    ];
  }

  private function get_show_count($widget_id) {
    if (empty($widget_id)) {
      return 5;
    }

    $sidebar = explode('-', $widget_id);
    $location = $sidebar[1] ?? 'content';

    switch ($location) {
      case 'sidebar':
        return 2;
      case 'content':
        return 3;
      default:
        return 5;
    }
  }

  private function render_widget_content($type, $title, $show, $cons_matches, $pages, $bg_color) {
    $wrapper_class = $type === 'table' ? 'kanews-gc-wrapper' : 'kanews-inline-card kgkdl15-H kanews-ticker-x';
    $section_class = $type === 'table' ? 'kanews-scroll kanews-gc' : '';
    $section_style = $type === 'table' ? 'style="max-height: 375px; ' . $bg_color . '"' : '';

    $slick_options = $type !== 'table' ? [
      'slidesToShow' => $show,
      'responsive' => [
        ['breakpoint' => 992, 'settings' => ['slidesToShow' => 3]],
        ['breakpoint' => 525, 'settings' => ['slidesToShow' => 2]]
      ]
    ] : [];

    ?>
    <div class="col-12">
      <div class="kanews-section <?php echo esc_attr($section_class); ?>" <?php echo $section_style; ?>>
        <?php 
        echo kanews_widget_title($title);
        $this->render_matches($type, $wrapper_class, $slick_options, $cons_matches, $pages);
        ?>
      </div>
    </div>

    <?php
  }

  private function render_matches($type, $wrapper_class, $slick_options, $cons_matches, $pages) {
    $counter = 0;
    $date = date('Y-m-d');
    $selected_leagues = $this->instance['game_center'] ?? $this->get_default_leagues();

    ?>
    <div class="<?php echo esc_attr($wrapper_class); ?>" <?php echo !empty($slick_options) ? 'data-slick=\'' . wp_json_encode($slick_options) . '\'' : ''; ?>>
      <?php
      if ($cons_matches) {
        // Maçları liglere göre grupla
        $matches_by_league = [];
        foreach ($cons_matches as $match) {
          if ($match['type'] == 1 && isset($match['league'])) {
            // Sadece seçili liglerdeki maçları göster
            if (in_array($match['league'], $selected_leagues)) {
              $league_id = $match['league'];
              if (!isset($matches_by_league[$league_id])) {
                $matches_by_league[$league_id] = [];
              }
              $matches_by_league[$league_id][] = $match;
            }
          }
        }

        // Her lig için maçları göster
        foreach ($matches_by_league as $league_matches) {
          if (!empty($league_matches)) {
            // Ligin maçlarını göster
            foreach ($league_matches as $match) {
              $counter++;
              $type === 'table' ? 
                $this->render_table_match($match) : 
                $this->render_ticker_match($match, $date);
            }
          }
        }
      }
      ?>
    </div>
    <?php
    $this->render_footer($counter, $pages, $date);
  }

  // Lig adını getiren yardımcı metod
  private function get_league_name($league_id) {
    $league_options = $this->get_league_options();
    return $league_options[$league_id] ?? '';
  }

  private function render_table_match($match) {
    $league_name = $this->get_league_name($match['league'] ?? '');
    ?>
    <div class="kanews-match-row" 
         aria-label="<?php echo esc_attr($league_name); ?>" 
         role="tooltip" 
         data-microtip-position="top"
         data-microtip-size="medium">
        <div class="kanews-match-content">
            <!-- Sol Takım -->
            <div class="kanews-team kanews-team-home">
                <span class="kanews-team-name"><?php echo esc_html($match['home']); ?></span>
                <?php if(isset($match['home-red-cards']) && $match['home-red-cards'] > 0): ?>
                    <span class="red-card-count"><?php echo esc_html($match['home-red-cards']); ?></span>
                <?php endif; ?>
                <?php echo kanews_get_local_image($match['home-logo'], ['width' => 32, 'height' => 32, 'alt' => esc_attr($match['home'])], '1e1'); ?>
            </div>

            <!-- Skor/Zaman Bölümü -->
            <div class="kanews-match-info">
                <?php if(isset($match['start']) && $match['start']): ?>
                    <div class="kanews-match-score">
                        <span class="<?php echo ($match['home-score'] > $match['away-score']) ? 'winning' : ''; ?>">
                            <?php echo esc_html($match['home-score']); ?>
                        </span>
                        <span class="score-divider">-</span>
                        <span class="<?php echo ($match['away-score'] > $match['home-score']) ? 'winning' : ''; ?>">
                            <?php echo esc_html($match['away-score']); ?>
                        </span>
                    </div>
                    
                    <?php if(isset($match['ht-home-score']) && $match['ht-home-score'] !== '' && isset($match['ht-away-score']) && $match['ht-away-score'] !== ''): ?>
                        <div class="kanews-match-ht-score">
                            <small>İY: <?php echo esc_html($match['ht-home-score']); ?> - <?php echo esc_html($match['ht-away-score']); ?></small>
                        </div>
                    <?php endif; ?>
                    
                    <?php if(isset($match['pen-home-score']) && $match['pen-home-score'] !== '' && isset($match['pen-away-score']) && $match['pen-away-score'] !== ''): ?>
                        <div class="kanews-match-pen-score">
                            <small>Pen: <?php echo esc_html($match['pen-home-score']); ?> - <?php echo esc_html($match['pen-away-score']); ?></small>
                        </div>
                    <?php endif; ?>
                    
                    <?php if(isset($match['agg-home-score']) && $match['agg-home-score'] !== '' && isset($match['agg-away-score']) && $match['agg-away-score'] !== ''): ?>
                        <div class="kanews-match-agg-score">
                            <small>Toplam: <?php echo esc_html($match['agg-home-score']); ?> - <?php echo esc_html($match['agg-away-score']); ?></small>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="kanews-match-time">
                        <?php echo esc_html($match['min']); ?>
                    </div>
                <?php endif; ?>

                <?php if(isset($match['min']) && !empty($match['min'])): ?>
                    <div class="kanews-match-status <?php echo $match['min'] === 'MS' ? 'status-finished' : 'status-live'; ?>">
                        <?php 
                        if($match['min'] == 'MS') {
                            echo esc_html($match['min']);
                        } elseif($match['min'] == 'HT') {
                            echo esc_html($match['min']);
                        } elseif(is_numeric($match['min'])) {
                            echo 'Devam Ediyor <span class="minute">' . esc_html($match['min']) . '</span>';
                        } else {
                            echo esc_html($match['min']);
                        }
                        ?>
                    </div>
                <?php else: ?>
                    <div class="kanews-match-status status-scheduled">
                        <?php echo esc_html($match['start']); ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Sağ Takım -->
            <div class="kanews-team kanews-team-away">
                <?php echo kanews_get_local_image($match['away-logo'], ['width' => 32, 'height' => 32, 'alt' => esc_attr($match['away'])], '1e1'); ?>
                <span class="kanews-team-name"><?php echo esc_html($match['away']); ?></span>
                <?php if(isset($match['away-red-cards']) && $match['away-red-cards'] > 0): ?>
                    <span class="red-card-count"><?php echo esc_html($match['away-red-cards']); ?></span>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php
  }

  private function render_ticker_match($match, $date) {
    $date_parts = explode('-', $date);
    ?>
    <div class="kanews-inline-card-item no-gutters">
        <div class="kanews-inline-card-summary col">
            <div class="kanews-inline-card-title d-flex justify-content-between">
                <div><?php echo esc_html($date_parts[2] . '.' . $date_parts[1]); ?></div>
                <?php if(isset($match['min']) && !empty($match['min'])): ?>
                    <?php if($match['min'] == 'MS'): ?>
                        <div class="color-success"><?php echo esc_html($match['min']); ?></div>
                    <?php elseif($match['min'] == 'HT'): ?>
                        <div class="color-warning"><?php echo esc_html($match['min']); ?></div>
                    <?php elseif(is_numeric($match['min'])): ?>
                        <div class="color-danger">Devam Ediyor <span class="minute"><?php echo esc_html($match['min']); ?></span></div>
                    <?php else: ?>
                        <div class="color-danger"><?php echo esc_html($match['min']); ?></div>
                    <?php endif; ?>
                <?php else: ?>
                    <span class="color-dark"><?php echo esc_html($match['start']); ?></span>
                <?php endif; ?>
                <?php if(isset($match['ht-home-score']) && $match['ht-home-score'] !== '' && isset($match['ht-away-score']) && $match['ht-away-score'] !== ''): ?>
                    <div class="kanews-inline-card-ht-score">
                        <small>İY: <?php echo esc_html($match['ht-home-score']); ?> - <?php echo esc_html($match['ht-away-score']); ?></small>
                    </div>
                <?php endif; ?>
                
                <?php if(isset($match['pen-home-score']) && $match['pen-home-score'] !== '' && isset($match['pen-away-score']) && $match['pen-away-score'] !== ''): ?>
                    <div class="kanews-inline-card-pen-score">
                        <small>Pen: <?php echo esc_html($match['pen-home-score']); ?> - <?php echo esc_html($match['pen-away-score']); ?></small>
                    </div>
                <?php endif; ?>
                
                <?php if(isset($match['agg-home-score']) && $match['agg-home-score'] !== '' && isset($match['agg-away-score']) && $match['agg-away-score'] !== ''): ?>
                    <div class="kanews-inline-card-agg-score">
                        <small>Toplam: <?php echo esc_html($match['agg-home-score']); ?> - <?php echo esc_html($match['agg-away-score']); ?></small>
                    </div>
                <?php endif; ?>
            </div>
            <div class="kanews-inline-card-content">
                <div class="kanews-inline-card-content-item d-flex justify-content-between">
                    <div>
                        <?php echo kanews_get_local_image($match['home-logo'], ['width' => 18, 'height' => 18, 'alt' => 'logo'], '1e1') . esc_html($match['home']); ?>
                        <?php if(isset($match['home-red-cards']) && $match['home-red-cards'] > 0): ?>
                            <span class="red-card-count"><?php echo esc_html($match['home-red-cards']); ?></span>
                        <?php endif; ?>
                    </div>
                    <div><?php echo isset($match['home-score']) ? esc_html($match['home-score']) : '-'; ?></div>
                </div>
                <div class="kanews-inline-card-content-item d-flex justify-content-between">
                    <div>
                        <?php echo kanews_get_local_image($match['away-logo'], ['width' => 18, 'height' => 18, 'alt' => 'logo'], '1e1') . esc_html($match['away']); ?>
                        <?php if(isset($match['away-red-cards']) && $match['away-red-cards'] > 0): ?>
                            <span class="red-card-count"><?php echo esc_html($match['away-red-cards']); ?></span>
                        <?php endif; ?>
                    </div>
                    <div><?php echo isset($match['away-score']) ? esc_html($match['away-score']) : '-'; ?></div>
                </div>
                
                
            </div>
        </div>
    </div>
    <?php
  }

  private function render_footer($counter, $pages, $date) {
    if (!$counter > 0):
        echo '<p style="font-size: 18px;padding:1em;margin-bottom:0">' . 
             sprintf(
                 esc_html__('Bugün (%s) için gösterilebilecek maç bulunmamaktadır, diğer liglere veya tarihlere göz atabilirsiniz.', 'kanews'),
                 esc_html($date)
             ) . '</p>';
    endif;
    
    if ($pages != '' && $pages != 'all') {
        echo '<a href="' . esc_url(get_page_link($pages)) . '" class="kanews-gc-load-more">' . 
             esc_html__('Daha Fazla Göster', 'kanews') . 
             '</a>';
    }
  }
}
?>