<?php
/* Template Name: Canlı Maçlar */
defined( 'ABSPATH' ) || exit; // Exit if accessed directly
global $wp;  
date_default_timezone_set('Europe/Istanbul');

// Datapicker
function wpse_enqueue_datepicker() {
  wp_enqueue_script( 'moment', 'https://cdn.jsdelivr.net/momentjs/latest/moment.min.js', array('jquery'), null, true );
  wp_enqueue_script( 'daterangepicker', 'https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js', array('jquery'), null, true );
  wp_enqueue_style( 'daterangepicker', 'https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css' );
  wp_add_inline_script( 'daterangepicker', "
  (function($) {
    'use strict';


      $('#datepicker').daterangepicker({
        'singleDatePicker': true,
        'minYear': 2023,
        'maxYear': 2024,
        'autoApply': true,
        'autoUpdateInput': false, 
        'endDate': '04/07/2023',
        'opens': 'left'
    }, function(start, end, label) {
      console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
    });
    


  })(jQuery)" );
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_datepicker' );
date_default_timezone_set('Europe/Istanbul');

// Set League and date
$lig = isset($_GET['lig']) ? esc_html($_GET['lig']) : 'all';
if(!isset($_GET['tarih']) || $_GET['tarih'] == '') {
  $date = date('Y-m-d');
} else {
  $date = esc_html($_GET['tarih']);
}

// Page title
$lig_title = kanews_correct_league_title2($lig);
$new_title = sprintf(esc_html__('%s Canlı Maç Sonuçları (%s)', 'kanews'), $lig_title, $date);
add_filter( 'pre_get_document_title', 'generate_custom_title', 10 );
add_filter( 'wpseo_title', 'generate_custom_title', 15 );
function generate_custom_title($title) {
  global $new_title;
  if(strpos($new_title, esc_html__( 'Tüm Maçlar', 'kanews' )) === false)
  return $new_title.' - '.get_bloginfo("name");  
  else
  return $title;
}

$leagues = [
  '4oogyu6o156iphvdvphwpck10' => 'Şampiyonlar Ligi',
  'c7b8o53flg36wbuevfzy3lb10' => 'Konferans Ligi',
  '4c1nfi2j1m731hcay25fcgndq' => 'UEFA Avrupa Ligi',
  '482ofyysbdbeoxauk19yg7tdt' => 'Süper Lig',
  '2o9svokc5s7diish3ycrzk7jm' => 'TFF 1. Lig',
  '2nttcoriwf5co73vmz1vr8frm' => 'TFF 2. Lig',
  '7af85xa75vozt2l4hzi6ryts7' => 'Türkiye Kupası',
  '2kwbbcootiqqgmrzs6o5inle5' => 'Premier Lig',
  '7ntvbsyq31jnzoqoa8850b9b8' => 'Championship',
  
  '6by3h89i2eykc341oz7lv1ddd' => 'Bundesliga',
  '34pl8szyvrbwcmfkuocjm3r6t' => 'La Liga',
  '1r097lpxe0xn03ihb7wi98kao' => 'Serie A',
  'dm5ka0os1e3dxcp3vh05kmp33' => 'Fransa Ligi',
  'akmkihra9ruad09ljapsm84b3' => 'Hollanda Ligi',
  '70excpe1synn9kadnbppahdn7' => 'Dünya Kupası',
  '39q1hq42hxjfylxb7xpe9bvf9' => 'Dünya Kupası Elemeleri',
  '8tddm56zbasf57jkkay4kbf11' => 'Avrupa Şampiyonası',
  'gfskxsdituog2kqp9yiu7bzi'  => 'Avrupa Şampiyonası Elemeleri',

  '595nsvo7ykvoe690b1e4u5n56' => 'Milletler Ligi',
  
  'a0f4gtru0oyxmpvty4thc5qkc' => 'Süper Kupa',
  
  'cesdwwnxbc5fmajgroc0hqzy2' => 'Milli Takım Hazırlık',
  '4nidzmunvpvxk1ir9b6m8mpay' => 'Hazırlık',
];


// $date = '2023-08-15';

$cons_matches = kanews_live_score_data($date, $leagues);
$cons_matches = json_decode($cons_matches, true);

// print_r($cons_matches);

if(!$cons_matches) {
  wp_redirect( get_the_permalink(), 301);
  die;
}


$counter = 0;
get_header(); 

?>
  <?php while ( have_posts() ) : the_post(); ?>
    <?php kanews_page_header($post->ID, $title, '', wp_sprintf( __('%1$s (%2$s ) canlı maç sonuçlarını anlık olarak takip edin! Güncel skorlar, puan durumu ve takım istatistikleri bir arada.', 'kanews'), $lig_title, $date), true); ?>
  <?php endwhile; ?>
  <?php do_action('kanews_header_ad'); ?>

<main id="main" class="site-main">
  <div class="container">
    <div class="row">
      <?php $insights = get_post_meta( get_the_ID(), 'post_insight', true ) == 1 ? 1 : 0; if(kanews_insights_control() == true || $insights == 0 ): ?>
       
        <div class="col-12 col-md-3">
          <div class="kanews-section widget widget_pages kanews-collapse-wrapper">
            <?php echo kanews_widget_title(esc_html__( 'Popüler Ligler', 'kanews' ), 'h3'); ?>
            
            <ul>
              <li class="page-item <?php if($lig == 'all') echo 'current_page_item'; ?>"><a href="<?php echo home_url(add_query_arg(array('tarih' => $date), $wp->request)); ?>"><?php esc_html_e( 'Tüm Maçlar', 'kanews' ); ?></a></li>
              <?php $counter = 0; foreach( $leagues as $key => $value ): $counter++; ?>
                <?php $collapse = $counter > 3 ? 'kanews-collapse-item hidden-mobile' : ''; ?>
                <li class="page-item <?php echo $collapse; ?> <?php if($lig == kanews_seflink( $value )) echo 'current_page_item'; ?>"><a href="<?php echo home_url(add_query_arg( array('lig' => kanews_seflink( $value ), 'tarih' => $date), $wp->request)); ?>">
                  <?php echo kanews_get_local_image(kanews_league_logo($value), $attr = array('width' => 22, 'height' => 22, 'alt' => 'logo', 'style' => 'margin-right: 15px'), '1e1'); ?>
                  <?php echo $value; ?></a>
                </li>
              <?php endforeach; ?>
            </ul>
            <div class="kanews-collapse-btn hidden-desktop"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" id="icon-angle-down"><path fill="currentColor" d="M17,9.17a1,1,0,0,0-1.41,0L12,12.71,8.46,9.17a1,1,0,0,0-1.41,0,1,1,0,0,0,0,1.42l4.24,4.24a1,1,0,0,0,1.42,0L17,10.59A1,1,0,0,0,17,9.17Z"></path></svg><span><?php esc_html_e( 'Daha Fazla Lig', 'kanews' ); ?></span></div>
          </div>
        </div>

        <div class="kanews-gc col-12 col-md-9">
        <input id="datepicker" readOnly="true" value="<?php echo $date == date('d/m/Y') ? '' : $date; ?>" placeholder="<?php esc_html_e( 'Bugünün Maçları', 'kanews' ); ?>"></input>
        <div class="kanews-gc-wrapper">
            <?php $counter = 0;
              foreach ($leagues as $key => $value) {
                if($cons_matches) {
                  $matches = array_values(kanews_live_score_filter_by_league_name($cons_matches, $key));
                  // print_r($matches);

                  if(($lig == 'all') || $lig == kanews_seflink($value)) {
    

                    $league_title = kanews_correct_league_title2($value);
                  
                    if(is_array($matches)  && !empty($matches)) {
                      

                      echo '<div class="kanews-section">';
                        echo kanews_widget_title(kanews_get_local_image(kanews_league_logo($value), $attr = array('width' => 22, 'height' => 22, 'alt' => 'logo', 'style' => 'margin-right: 15px'), '1e1').$league_title, 'h3');
                        foreach ($matches as $match) {
                          if($match['type'] == 1) {
                            $counter++;
                            echo '<div class="kanews-gc-item d-flex justify-content-between align-items-center flex-wrap">';

                              // echo  '<div class="kanews-gc-item-date hidden-mobile col-lg-1">'.explode('-', $date)[0].'-'.explode('-', $date)[2].'</div>';

                              echo  '<div class="kanews-gc-item-detail ml-auto col d-flex flex-wrap align-items-center">
                                <div class="d-flex flex-wrap align-items-center justify-content-center col">

                                  <div class="kanews-gc-item-home col">
                                    <div class="d-flex justify-content-end align-items-center">
                                                                          '.(isset($match['home-red-cards']) && $match['home-red-cards'] > 0 ? '<span class="red-card-count">'.$match['home-red-cards'].'</span>' : '').'

                                      <span class="truncate truncate-1">'.$match['home'].'</span>
                                      '.kanews_get_local_image($match['home-logo'], $attr = array('width' => 32, 'height' => 32, 'alt' => 'logo'), '1e1').'
                                    </div>
                                  </div>

                                  <div class="kanews-gc-item-time m-0 d-flex flex-column">';
                                    if($match['home-score'] !== '' && $match['away-score'] !== '') {
                                      echo '<div class="kanews-gc-item-time-score">';
                                        echo  ($match['home-score'] > $match['away-score']) ? '<span class="color-success">' : '<span>';
                                          echo $match['home-score'];
                                        echo '</span> - ';
                                        echo  ($match['away-score'] > $match['home-score']) ? '<span class="color-dark">' : '<span>';
                                          echo $match['away-score'];
                                        echo '</span>';
                                      echo '</div>';
                                      
                                      // Display half-time score if available
                                      if(isset($match['ht-home-score']) && $match['ht-home-score'] !== '' && isset($match['ht-away-score']) && $match['ht-away-score'] !== '') {
                                        echo '<div class="kanews-gc-item-ht-score">';
                                          echo '<small>İY: '.$match['ht-home-score'].' - '.$match['ht-away-score'].'</small>';
                                        echo '</div>';
                                      }
                                      
                                      // Display penalty score if available
                                      if(isset($match['pen-home-score']) && $match['pen-home-score'] !== '' && isset($match['pen-away-score']) && $match['pen-away-score'] !== '') {
                                        echo '<div class="kanews-gc-item-pen-score">';
                                          echo '<small>Pen: '.$match['pen-home-score'].' - '.$match['pen-away-score'].'</small>';
                                        echo '</div>';
                                      }
                                      
                                      // Display aggregate score if available
                                      if(isset($match['agg-home-score']) && $match['agg-home-score'] !== '' && isset($match['agg-away-score']) && $match['agg-away-score'] !== '') {
                                        echo '<div class="kanews-gc-item-agg-score">';
                                          echo '<small>Toplam: '.$match['agg-home-score'].' - '.$match['agg-away-score'].'</small>';
                                        echo '</div>';
                                      }
                                    } else {
                                      echo '<span>'.$match['start'].'</span>';
                                    }
                                  echo '</div>

                                  <div class="kanews-gc-item-away col">
                                    <div class="d-flex justify-content-start align-items-center">
                                      '.kanews_get_local_image($match['away-logo'], $attr = array('width' => 32, 'height' => 32, 'alt' => 'logo'), '1e1').'
                                      <span class="truncate truncate-1">'.$match['away'].'</span>
                                      '.(isset($match['away-red-cards']) && $match['away-red-cards'] > 0 ? '<span class="red-card-count">'.$match['away-red-cards'].'</span>' : '').'
                                    </div>
                                  </div>

                                </div>
                              </div>';

                              echo '<div class="kanews-gc-item-right col-lg-2 text-right">';
                                if(isset($match['min']) && !empty($match['min'])) {
                                  if( $match['min'] == 'MS' ) {
                                    echo '<div class="kanews-gc-label bg-success">'.$match['min'].' </div>';
                                  } else if( $match['min'] == 'HT' ) {
                                    echo '<div class="kanews-gc-label bg-warning">'.$match['min'].' </div>';
                                  } else if( is_numeric($match['min']) ) {
                                    echo '<div class="kanews-gc-label bg-danger">Devam Ediyor <span class="minute">'.$match['min'].'</span></div>';
                                  } else {
                                    echo '<div class="kanews-gc-label bg-danger">'.$match['min'].' </div>';
                                  }
                                } else {
                                  echo '<span class="kanews-gc-label bg-dark">'.$match['start'].'</span>';
                                }
                              echo '</div>';

                            echo '</div>';
                          }
                        }
                      // break;
                      echo '</div>';
                    }
                    
                  }
                }
              }
              if($counter < 1)
              echo '<div class="kanews-section">'.kanews_widget_title(esc_html__( 'Maç Bulunamadı', 'kanews' )).'<p style="font-size: 18px;padding:1em;margin-bottom:0">'.sprintf(esc_html__( ' %s için gösterilebilecek %s tarihli maç veye maçlar bulunmamaktadır, diğer liglere veya tarihlere göz atabilirsiniz.', 'kanews' ),  kanews_correct_league_title2($lig), $date).'</p></div>';
            ?>
          </div>
        </div>

        <?php if( $league_title != 'Tüm Maçlar' ): ?>
          <div class="col-12">
            <?php get_template_part('template-parts/content/components/related', 'page2', array( 
              'posts_per_page' => 20,
              's' => sanitize_text_field($league_title) 
            ) ); ?>
          </div>
          
        <?php else: ?>
          <?php get_template_part('template-parts/content/components/related', 'page'); ?>
        <?php endif; ?>


      <?php else: ?>
        <div class="col-12"><?php echo kanews_private_content('a'); ?></div>
      <?php endif; ?>
    </div>
  </div>
</main>
<script>
    window.onload = function() {
      jQuery('#datepicker').on('apply.daterangepicker', function(ev, picker) {
        var date = jQuery(this).val();
        window.location = '<?php echo home_url(add_query_arg(array('lig' => $lig, 'tarih' => "'+picker.endDate.format('YYYY-MM-DD')"), $wp->request)); ?>
      });
      
      // Auto refresh match data every 60 seconds if there are live matches
      var hasLiveMatches = jQuery('.kanews-gc-label.bg-danger').length > 0;
      if (hasLiveMatches) {
        setInterval(function() {
          location.reload();
        }, 60000); // Refresh every 60 seconds
      }
    }
</script>

<?php 
get_footer();

