<?php
/**
 * Template Name: Borsa
 * @theme kanews
 * @developer kanthemes.com
 */
__( 'Borsa', 'kanews' );
defined( 'ABSPATH' ) || exit; // Exit if accessed directly
$hisse = isset($_GET['hisse']) ? esc_html(strtoupper($_GET['hisse'])) : NULL;

$response = get_local_file_contents(KAN_TEMPLATE_PATH."/inc/api/exchange/exchange.json");
$data = json_decode($response);

// Fetch BIST 100 CSV data
$bist100_csv_data = null;
$csv_url = 'https://uzmanpara.milliyet.com.tr/ana_sayfa_grafik_data.csv?_=' . time();
$csv_response = wp_remote_get($csv_url, array(
  'timeout' => 15,
  'sslverify' => false,
  'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
));

if (!is_wp_error($csv_response) && wp_remote_retrieve_response_code($csv_response) === 200) {
  $csv_body = wp_remote_retrieve_body($csv_response);
  if (!empty($csv_body)) {
    $bist100_csv_data = $csv_body;
  }
}

if($hisse != NULL) {

  if(empty($data) || !is_object($data) || !isset($data->$hisse->satis)) {
    wp_redirect( get_the_permalink(), 301);
    die;
  }
  
  $new_title = wp_sprintf( esc_html__('%1$s — Hisse Senedi Grafiği ve Piyasa Değeri', 'kanews'), $hisse ).' - '.get_bloginfo( 'name' );
  

  function generate_custom_title($title) {
    global $new_title;
    if($new_title)
    $title = $new_title;
    return $title;  
  }
  add_filter( 'pre_get_document_title', 'generate_custom_title', 10 );
  add_filter( 'wpseo_title', 'generate_custom_title', 15 );
}

$lang = get_locale();
if ( strlen( $lang ) > 0 ) {
$lang = explode( '_', $lang )[0];
}

get_header(); ?>
  <?php while ( have_posts() ) : the_post(); ?>

    <?php kanews_page_header($post->ID); ?>

  <?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 ): ?>
    
          <?php if($hisse == NULL) : ?>
            
            <div class="col-12 col-lg-8">
              <div class="kanews-section">
                <?php echo kanews_widget_title(esc_html__( 'Hisse Senetleri', 'kanews' ), 'h2'); ?>
                <div class="p-1">
                <!-- Tab Navigation -->
                <div class="d-flex flex-wrap align-items-center justify-content-between g-10">
                  <div class="d-flex align-items-center g-10" style="overflow-x: auto;">
                    <button class="kanews-label stock-tab-btn active shrink-0" data-tab="all"><?php _e('Tüm Hisseler', 'kanews'); ?></button>
                    <button class="kanews-label stock-tab-btn shrink-0" data-tab="rising"><?php _e('En Çok Artanlar', 'kanews'); ?></button>
                    <button class="kanews-label stock-tab-btn shrink-0" data-tab="falling"><?php _e('En Çok Azalanlar', 'kanews'); ?></button>
                  </div>
                  <div style="flex: 0 0 auto;">
                    <input type="text" placeholder="<?php _e('Hisse ara', 'kanews'); ?>" id="kanews-currencies-search" class="kanews-label" style="min-width: 200px;">
                  </div>
                </div>

                <div class="empty-height" style="height: 15px;"></div>
                
                <!-- Alphabet Filter -->
                <div class="d-flex align-items-center g-10 " style="overflow-x: auto;">
                  <?php 
                  $letters = range('A', 'Z');
                  foreach($letters as $letter) {
                    echo '<button class="kanews-label alphabet-filter-btn" data-letter="'.$letter.'">'.$letter.'</button>';
                  }
                  ?>
                </div>
                
                </div>
                
                <hr class="hr-widget">
                
                <div class="kanews-scroll" style="max-height: 725px">
                  <table class="kanews-table table-search table-currencies" id="stocks-table">
                  <thead>
                    <tr>
                      <th><span class="nobr"><?php esc_html_e( 'Menkul', 'kanews' ); ?></span></th>
                      <th><span class="nobr"><?php esc_html_e( 'Alış', 'kanews' ); ?></span></th>
                      <th><span class="nobr"><?php esc_html_e( 'Satış', 'kanews' ); ?></span></th>
                      <th><span class="nobr"><?php esc_html_e( 'Değişim', 'kanews' ); ?></span></th>
                      <th><span class="nobr"><?php esc_html_e( 'Güncelleme', 'kanews' ); ?></span></th>
                    </tr>
                  </thead>
                  <tbody id="stocks-tbody">
                    <?php
                
                    if(!empty($data)) {
                      foreach($data as $key=>$value) {
                        echo '<tr onclick="window.location=\''.kanews_get_page_link('hisse', $key, 'exchange').'\';" data-code="'. $key.'" data-letter="'.strtoupper(substr($key, 0, 1)).'">';

                          echo '<td style="font-weight: 700"><h3><a href="'.kanews_get_page_link('hisse', $key, 'exchange').'">'.$key.'</a></h3></td>';
                          if(isset($value->alis)) echo '<td>'.$value->alis.'</td>';
                          if(isset($value->satis)) echo '<td>'.$value->satis.'</td>';
                          if(isset($value->degisim)) {
                            if ($value->degisim < 0) {
                              $class = 'color-danger';
                              $icon = '<i class="icon-caret icon-180deg icon-2x"></i>';
                            } else {
                              $class = 'color-success';
                              $icon = '<i class="icon-caret icon-2x"></i>';
                            }
                            echo '<td class="'.$class.'" data-change="'.floatval($value->degisim).'">'.$value->degisim.'</td>';
                            if(isset($value->tarih)) echo '<td>'.$value->tarih.'</td>';
                          }
                        echo '</tr>';

                      }
                    } else {
                      echo '<tr><td colspan="5">'.esc_html__( 'Veri alınamadı!', 'kanews' ).'</td></tr>';
                    }
                    ?>
                  </tbody>
                </table>
              </div>
              </div>
            </div>
            
            <script type="text/javascript">
            (function() {
              var allRows = [];
              var currentTab = 'all';
              var currentLetter = null;
              
              // Store all rows
              document.addEventListener('DOMContentLoaded', function() {
                var tbody = document.getElementById('stocks-tbody');
                if (tbody) {
                  allRows = Array.from(tbody.querySelectorAll('tr'));
                }
                
                // Tab button handlers
                var tabButtons = document.querySelectorAll('.stock-tab-btn');
                tabButtons.forEach(function(btn) {
                  btn.addEventListener('click', function() {
                    // Update active state
                    tabButtons.forEach(function(b) {
                      b.classList.remove('active');
                      b.style.backgroundColor = '';
                      b.style.color = '';
                    });
                    this.classList.add('active');
                    this.style.backgroundColor = '#424242';
                    this.style.color = '#fff';
                    
                    currentTab = this.getAttribute('data-tab');
                    filterStocks();
                  });
                });
                
                // Alphabet filter handlers
                var alphabetButtons = document.querySelectorAll('.alphabet-filter-btn');
                alphabetButtons.forEach(function(btn) {
                  btn.addEventListener('click', function() {
                    // Toggle active state
                    if (this.classList.contains('active')) {
                      this.classList.remove('active');
                      this.style.backgroundColor = '';
                      this.style.color = '';
                      currentLetter = null;
                    } else {
                      alphabetButtons.forEach(function(b) {
                        b.classList.remove('active');
                        b.style.backgroundColor = '';
                        b.style.color = '';
                      });
                      this.classList.add('active');
                      this.style.backgroundColor = '#424242';
                      this.style.color = '#fff';
                      currentLetter = this.getAttribute('data-letter');
                    }
                    filterStocks();
                  });
                });
                
                // Search handler
                var searchInput = document.getElementById('kanews-currencies-search');
                if (searchInput) {
                  searchInput.addEventListener('input', function() {
                    filterStocks();
                  });
                }
              });
              
              function filterStocks() {
                var tbody = document.getElementById('stocks-tbody');
                if (!tbody) return;
                
                var searchTerm = document.getElementById('kanews-currencies-search') ? document.getElementById('kanews-currencies-search').value.toLowerCase() : '';
                var visibleRows = [];
                
                allRows.forEach(function(row) {
                  var code = row.getAttribute('data-code') || '';
                  var letter = row.getAttribute('data-letter') || '';
                  var changeEl = row.querySelector('[data-change]');
                  var change = changeEl ? parseFloat(changeEl.getAttribute('data-change')) || 0 : 0;
                  
                  var show = true;
                  
                  // Tab filter
                  if (currentTab === 'all') {
                    // Show all stocks
                    show = true;
                  } else if (currentTab === 'rising') {
                    show = change > 0;
                  } else if (currentTab === 'falling') {
                    show = change < 0;
                  }
                  
                  // Letter filter
                  if (show && currentLetter && letter !== currentLetter) {
                    show = false;
                  }
                  
                  // Search filter
                  if (show && searchTerm && code.toLowerCase().indexOf(searchTerm) === -1) {
                    show = false;
                  }
                  
                  if (show) {
                    visibleRows.push(row);
                    row.style.display = '';
                  } else {
                    row.style.display = 'none';
                  }
                });
                
                // Sort for rising/falling tabs
                if (currentTab === 'rising' || currentTab === 'falling') {
                  visibleRows.sort(function(a, b) {
                    var changeElA = a.querySelector('[data-change]');
                    var changeElB = b.querySelector('[data-change]');
                    var changeA = changeElA ? parseFloat(changeElA.getAttribute('data-change')) || 0 : 0;
                    var changeB = changeElB ? parseFloat(changeElB.getAttribute('data-change')) || 0 : 0;
                    if (currentTab === 'rising') {
                      return changeB - changeA; // Descending
                    } else {
                      return changeA - changeB; // Ascending
                    }
                  });
                  
                  // Reorder in DOM
                  visibleRows.forEach(function(row) {
                    tbody.appendChild(row);
                  });
                }
                
                // Show message if no results
                if (visibleRows.length === 0) {
                  var noResults = tbody.querySelector('.no-results');
                  if (!noResults) {
                    noResults = document.createElement('tr');
                    noResults.className = 'no-results';
                    noResults.innerHTML = '<td colspan="5" style="text-align: center; padding: 20px;"><?php esc_html_e( 'Sonuç bulunamadı', 'kanews' ); ?></td>';
                    tbody.appendChild(noResults);
                  }
                } else {
                  var noResults = tbody.querySelector('.no-results');
                  if (noResults) {
                    noResults.remove();
                  }
                }
              }
            })();
            </script>
            
     

            <!-- BIST 100 Chart Section -->
            <div class="col-12 col-lg-4">
              <div class="kanews-section">
                <?php echo kanews_widget_title(esc_html__( 'BIST 100 Grafiği', 'kanews' ), 'h2'); ?>
                
                <!-- BIST 100 Last Data Info -->
                <div class="p-1" id="bist100-last-data" style="display: none;">
                  <div class="kanews-article-header p-0 mb-1">
                    <div class="d-flex align-items-center g-10 mb-1">
                      <img loading="lazy" src="https://s3-symbol-logo.tradingview.com/country/TR.svg" width="48" height="48" alt="BIST 100">
                      <h3 class="kanews-article-title mb-0">BIST 100</h3>
                    </div>
                    <p id="bist100-description"></p>
                    
                    <div class="d-flex flex-wrap align-items-center mt-1 g-10">
                      <h4 style="font-size: 2rem">
                        <strong id="bist100-last-close"></strong> 
                        <span style="font-weight: 400"><?php esc_html_e( 'Türk Lirası', 'kanews' ); ?></span>
                      </h4>
                    </div>
                  </div>

                  <div class="mt-0">
                    <ul class="row">
                      <li class="col-auto mb-1">
                        <div class="kanews-mgfsa14"><?php esc_html_e( 'Yüksek', 'kanews' ); ?></div>
                        <div class="kanews-mgfsa141" id="bist100-last-high"><span class="currency">TRY</span></div>
                      </li>
                      <li class="col-auto mb-1">
                        <div class="kanews-mgfsa14"><?php esc_html_e( 'Düşük', 'kanews' ); ?></div>
                        <div class="kanews-mgfsa141" id="bist100-last-low"><span class="currency">TRY</span></div>
                      </li>
                      <li class="col-auto">
                        <div class="kanews-mgfsa14"><?php esc_html_e( 'Değişim', 'kanews' ); ?></div>
                        <div class="kanews-mgfsa141" id="bist100-last-change"><span class="currency">%</span></div>
                      </li>
                      <li class="col-auto">
                        <div class="kanews-mgfsa14"><?php esc_html_e( 'Hacim', 'kanews' ); ?></div>
                        <div class="kanews-mgfsa141" id="bist100-last-volume"></div>
                      </li>
                      <li class="col-auto">
                        <div class="kanews-mgfsa14"><?php esc_html_e( 'Son Güncelleme', 'kanews' ); ?></div>
                        <div class="kanews-mgfsa141" id="bist100-last-time"></div>
                      </li>
                    </ul>
                  </div>
                </div>
                
                <div id="bist100-chart-container" style="width: 100%; height: 500px; min-width: 310px;"></div>
                
                <script type="text/javascript">
                (function() {
                  // CSV data from PHP
                  var csvData = <?php echo $bist100_csv_data ? json_encode($bist100_csv_data) : 'null'; ?>;
                  
                  // Process CSV data
                  function processBIST100Data() {
                    if (!csvData) {
                      var container = document.getElementById('bist100-chart-container');
                      if (container) {
                        container.innerHTML = '<div style="text-align: center; padding: 40px; color: #999;"><?php esc_html_e( 'Grafik verisi yüklenirken hata oluştu', 'kanews' ); ?></div>';
                      }
                      return;
                    }
                    
                    processCSVData(csvData);
                  }
                  
                  function displayLastData(data) {
                    var infoBox = document.getElementById('bist100-last-data');
                    if (!infoBox) return;
                    
                    // Format numbers
                    var formatNumber = function(num) {
                      return num.toLocaleString('tr-TR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                    };
                    
                    var formatNumberSimple = function(num) {
                      return num.toLocaleString('tr-TR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                    };
                    
                    var formatVolume = function(num) {
                      if (num >= 1000000000) {
                        return (num / 1000000000).toFixed(2) + ' Milyar';
                      } else if (num >= 1000000) {
                        return (num / 1000000).toFixed(2) + ' Milyon';
                      } else if (num >= 1000) {
                        return (num / 1000).toFixed(2) + ' Bin';
                      }
                      return num.toLocaleString('tr-TR');
                    };
                    
                    // Set values
                    var closeEl = document.getElementById('bist100-last-close');
                    var changeEl = document.getElementById('bist100-last-change');
                    var highEl = document.getElementById('bist100-last-high');
                    var lowEl = document.getElementById('bist100-last-low');
                    var volumeEl = document.getElementById('bist100-last-volume');
                    var timeEl = document.getElementById('bist100-last-time');
                    var descEl = document.getElementById('bist100-description');
                    
                    // Description
                    if (descEl) {
                      var changeText = (data.changePercent >= 0 ? '+' : '') + data.changePercent + '%';
                      descEl.textContent = 'BIST 100 anlık olarak ' + formatNumberSimple(data.close) + ' Türk Lirası fiyatından işlem görmektedir. Fiyatı son 24 saatte ' + changeText + ' değişim göstermiştir.';
                    }
                    
                    if (closeEl) closeEl.textContent = formatNumberSimple(data.close);
                    if (highEl) {
                      highEl.innerHTML = formatNumberSimple(data.high) + ' <span class="currency">TRY</span>';
                    }
                    if (lowEl) {
                      lowEl.innerHTML = formatNumberSimple(data.low) + ' <span class="currency">TRY</span>';
                    }
                    if (volumeEl) volumeEl.textContent = formatVolume(data.volume);
                    
                    // Format time
                    var date = new Date(data.timestamp);
                    var timeStr = date.toLocaleTimeString('tr-TR', {hour: '2-digit', minute: '2-digit', second: '2-digit'});
                    if (timeEl) timeEl.textContent = timeStr;
                    
                    // Set change with color
                    if (changeEl) {
                      var changeText = (data.changePercent >= 0 ? '+' : '') + data.changePercent;
                      changeEl.innerHTML = changeText + '<span class="currency">%</span>';
                      changeEl.className = 'kanews-mgfsa141 ' + (data.change >= 0 ? 'color-success' : 'color-danger');
                    }
                    
                    // Show info box
                    infoBox.style.display = 'block';
                  }
                  
                  function processCSVData(csvText) {
                    var lines = csvText.trim().split('\n');
                    var ohlc = [];
                    var volume = [];
                    
                    // Skip header if exists, process data lines
                    for (var i = 0; i < lines.length; i++) {
                      var line = lines[i].trim();
                      if (!line) continue;
                      
                      // Parse CSV line: date/time, open, high, low, close, volume
                      var parts = line.split(',');
                      if (parts.length >= 6) {
                        var dateTimeStr = parts[0].trim();
                        var open = parseFloat(parts[1]);
                        var high = parseFloat(parts[2]);
                        var low = parseFloat(parts[3]);
                        var close = parseFloat(parts[4]);
                        var vol = parseFloat(parts[5]);
                        
                        // Parse date/time: format is "2025-11-14/10:00:00"
                        var dateTimeParts = dateTimeStr.split('/');
                        if (dateTimeParts.length === 2) {
                          var dateStr = dateTimeParts[0];
                          var timeStr = dateTimeParts[1];
                          var dateTime = new Date(dateStr + 'T' + timeStr);
                          var timestamp = dateTime.getTime();
                          
                          if (!isNaN(timestamp) && !isNaN(open) && !isNaN(high) && !isNaN(low) && !isNaN(close)) {
                            ohlc.push([timestamp, open, high, low, close]);
                            volume.push([timestamp, vol]);
                          }
                        }
                      }
                    }
                    
                    // Sort by timestamp
                    ohlc.sort(function(a, b) {
                      return a[0] - b[0];
                    });
                    volume.sort(function(a, b) {
                      return a[0] - b[0];
                    });
                    
                    if (ohlc.length > 0) {
                      // Get last data for display
                      var lastData = ohlc[ohlc.length - 1];
                      var lastVolume = volume[volume.length - 1];
                      var firstData = ohlc[0];
                      
                      // Calculate change
                      var lastClose = lastData[4]; // close
                      var firstClose = firstData[4]; // first close
                      var change = lastClose - firstClose;
                      var changePercent = firstClose > 0 ? ((change / firstClose) * 100).toFixed(2) : 0;
                      
                      // Display last data
                      displayLastData({
                        close: lastClose,
                        high: lastData[2],
                        low: lastData[3],
                        open: lastData[1],
                        volume: lastVolume[1],
                        timestamp: lastData[0],
                        change: change,
                        changePercent: changePercent
                      });
                      
                      createBIST100Chart(ohlc, volume);
                    } else {
                      var container = document.getElementById('bist100-chart-container');
                      if (container) {
                        container.innerHTML = '<div style="text-align: center; padding: 40px; color: #999;"><?php esc_html_e( 'Veri bulunamadı', 'kanews' ); ?></div>';
                      }
                    }
                  }
                  
                  function createBIST100Chart(ohlc, volume) {
                    // Check if Highcharts is loaded
                    if (typeof Highcharts === 'undefined') {
                      // Load Highcharts if not already loaded
                      var script = document.createElement('script');
                      script.src = 'https://code.highcharts.com/stock/highstock.js';
                      script.onload = function() {
                        renderChart(ohlc, volume);
                      };
                      document.head.appendChild(script);
                    } else {
                      renderChart(ohlc, volume);
                    }
                  }
                  
                  function renderChart(ohlc, volume) {
                    Highcharts.stockChart('bist100-chart-container', {
                      chart: {
                        height: 500
                      },
                      rangeSelector: {
                        enabled: false
                      },
                      title: {
                        text: 'BIST 100 - Gün İçi Grafik'
                      },
                      xAxis: {
                        dateTimeLabelFormats: {
                          millisecond: '%H:%M:%S',
                          second: '%H:%M:%S',
                          minute: '%H:%M',
                          hour: '%H:%M',
                          day: '%H:%M',
                          week: '%e %b',
                          month: '%b \'%y',
                          year: '%Y'
                        }
                      },
                      yAxis: [{
                        labels: {
                          align: 'right',
                          x: -3
                        },
                        title: {
                          text: 'Fiyat'
                        },
                        height: '60%',
                        lineWidth: 2
                      }, {
                        labels: {
                          align: 'right',
                          x: -3
                        },
                        title: {
                          text: 'Hacim'
                        },
                        top: '65%',
                        height: '35%',
                        offset: 0,
                        lineWidth: 2
                      }],
                      tooltip: {
                        split: true,
                        formatter: function() {
                          var points = this.points || [this.point];
                          var tooltip = '<b>' + Highcharts.dateFormat('%H:%M - %e %b %Y', points[0].x) + '</b><br/>';
                          points.forEach(function(point) {
                            if (point.series.name === 'Hacim') {
                              tooltip += '<span style="color:' + point.color + '">\u25CF</span> ' + point.series.name + ': <b>' + Highcharts.numberFormat(point.y, 0) + '</b><br/>';
                            } else {
                              if (point.open !== undefined) {
                                tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Açılış: <b>' + Highcharts.numberFormat(point.open, 2) + '</b><br/>';
                                tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Yüksek: <b>' + Highcharts.numberFormat(point.high, 2) + '</b><br/>';
                                tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Düşük: <b>' + Highcharts.numberFormat(point.low, 2) + '</b><br/>';
                                tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Kapanış: <b>' + Highcharts.numberFormat(point.close, 2) + '</b><br/>';
                              } else {
                                tooltip += '<span style="color:' + point.color + '">\u25CF</span> ' + point.series.name + ': <b>' + Highcharts.numberFormat(point.y, 2) + '</b><br/>';
                              }
                            }
                          });
                          return tooltip;
                        }
                      },
                      series: [{
                        type: 'candlestick',
                        name: 'BIST 100',
                        data: ohlc,
                        id: 'primary',
                        upColor: '#26a69a',
                        color: '#ef5350',
                        lineColor: '#26a69a',
                        upLineColor: '#26a69a'
                      }, {
                        type: 'column',
                        name: 'Hacim',
                        data: volume,
                        yAxis: 1,
                        color: '#90EE90'
                      }],
                      navigator: {
                        enabled: false
                      },
                      scrollbar: {
                        enabled: false
                      },
                      credits: {
                        enabled: false
                      },
                      lang: {
                        loading: 'Yükleniyor...',
                        months: ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'],
                        weekdays: ['Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi'],
                        shortMonths: ['Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara']
                      }
                    });
                  }
                  
                  // Initialize on page load
                  document.addEventListener('DOMContentLoaded', function() {
                    processBIST100Data();
                  });
                })();
                </script>
              </div>
            </div>

            <div class="col-12 col-lg-8">
              <div class="kanews-section">
                <?php echo kanews_widget_title(esc_html__( 'Endeksler', 'kanews' ), 'h2'); ?>
                <!-- TradingView Widget BEGIN -->
                <div class="tradingview-widget-container">
                  <div class="tradingview-widget-container__widget"></div>
                  <div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/markets/" rel="noopener" target="_blank"><span class="blue-text">Market summary</span></a> by TradingView</div>
                  <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-market-quotes.js" async>
                  {
                  "width": "100%",
                  "height": "425",
                  "symbolsGroups": [
                    {
                      "name": "Indices",
                      "originalName": "Indices",
                      "symbols": [
                        {
                          "name": "CAPITALCOM:DXY",
                          "displayName": "DXY"
                        },
                        {
                          "name": "FOREXCOM:SPXUSD",
                          "displayName": "S&P 500"
                        },
                        {
                          "name": "FOREXCOM:NSXUSD",
                          "displayName": "US 100"
                        },
                        {
                          "name": "FOREXCOM:DJI",
                          "displayName": "Dow 30"
                        },
                        {
                          "name": "INDEX:NKY",
                          "displayName": "Nikkei 225"
                        },
                        {
                          "name": "INDEX:DEU40",
                          "displayName": "DAX Index"
                        },
                        {
                          "name": "FOREXCOM:UKXGBP",
                          "displayName": "UK 100"
                        },
                        {
                          "name": "BIST:XU100",
                          "displayName": "BIST 100"
                        },
                        {
                          "name": "BIST:XU050",
                          "displayName": "BIST 50"
                        },
                        {
                          "name": "BIST:XU030",
                          "displayName": "BIST 30"
                        },
                        {
                          "name": "BIST:XBANK",
                          "displayName": "BIST Banka"
                        }
                      ]
                    }
                  ],
                  "showSymbolLogo": true,
                  "colorTheme": "light",
                  "isTransparent": false,
                  "locale": "<?php echo $lang; ?>"
                }
                  </script>
                </div>
                <!-- TradingView Widget END -->
              </div>
            </div>

            <div class="col-12 col-lg-4">
              <div class="kanews-section">
              <?php echo kanews_widget_title(esc_html__( 'Ekonomik Takvim', 'kanews' ), 'h2'); ?>
                <!-- TradingView Widget BEGIN -->
                <div class="tradingview-widget-container">
                  <div class="tradingview-widget-container__widget"></div>
                  <div class="tradingview-widget-copyright"><a href="https://tr.tradingview.com/economic-calendar/" rel="noopener" target="_blank"><span class="blue-text">Ekonomik takvim</span></a> TradingView tarafından</div>
                  <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-events.js" async>
                  {
                  "width": "100%",
                  "height": "425",
                  "colorTheme": "light",
                  "isTransparent": false,
                  "locale": "tr",
                  "importanceFilter": "0,1",
                  "currencyFilter": "USD,EUR,TRL"
                }
                  </script>
                </div>
                <!-- TradingView Widget END -->
              </div>
            </div>
            <div class="col-12">
              <!-- TradingView Widget BEGIN -->
<div class="tradingview-widget-container">
  <div class="tradingview-widget-container__widget"></div>
  <div class="tradingview-widget-copyright"><a href="https://tr.tradingview.com/" rel="noopener nofollow" target="_blank"><span class="blue-text">Tüm piyasaları TradingView üzerinden takip edin</span></a></div>
  <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-stock-heatmap.js" async>
  {
  "exchanges": [],
  "dataSource": "BIST100",
  "grouping": "sector",
  "blockSize": "market_cap_basic",
  "blockColor": "change",
  "locale": "tr",
  "symbolUrl": "",
  "colorTheme": "light",
  "hasTopBar": true,
  "isDataSetEnabled": true,
  "isZoomEnabled": true,
  "hasSymbolTooltip": true,
  "width": "100%",
  "height": "1000"
}
  </script>
</div>
<!-- TradingView Widget END -->
            </div>
    
            
            <?php while ( have_posts() ) : the_post(); 
              if ($post->post_content): ?>
                <div class="col-12">
                  <div class="kanews-article kanews-section-flat kanews-article-1">
                    <div class="kanews-article-content entry-content">
                      <?php the_content(); ?>
                    </div>
                  </div>
                </div>
              <?php endif; ?>
            <?php endwhile; ?>

            <?php get_template_part('template-parts/content/components/related', 'page'); ?>
          <?php else: $change =  $data->$hisse->degisim; ?>

            <div class="col-12">

              <div class="single-layout-flat">
                <div class="kanews-section-box">
                  <div class="kanews-article-header p-0 mb-1">
                  <div class="d-flex align-items-center g-10 mb-1">
                    <img loading="lazy" src="https://s3-symbol-logo.tradingview.com/country/TR.svg" width="48" height="48" alt="<?php echo esc_attr($hisse); ?>" />
                    <h2 class="kanews-article-title mb-0"><?php echo $hisse; ?></h2>
                    </div>
                    <h3 style="font-weight:400"><?php $page_desc = sprintf(esc_html__('%1$s anlık olarak %2$s fiyatından işlem görmektedir. Fiyatı son 24 saatte %3$s%% değişim göstermiştir..', 'kanews'), $hisse, currency_format_number($data->$hisse->satis).' '.esc_html__( 'Türk Lirası', 'kanews' ), $change ); echo $page_desc; ?></h3>
                    
                    <div class="d-flex flex-wrap align-items-center mt-1 g-10">
                    <?php 
                    echo '<div style="font-size: 2rem">';
                    echo '<strong>'.$data->$hisse->satis.'</strong> ';
                    echo esc_html__( 'Türk Lirası', 'kanews' );
                    echo '</div>';
          
                    ?>
                    </div>
        
                  </div>

                  <div class="mt-0">
                    <ul class="row">
                      <li class="col-auto mb-1">
                        <div class="kanews-mgfsa14"><?php esc_html_e( 'Alış', 'kanews' ); ?></div>
                        <div class="kanews-mgfsa141"><?php echo $data->$hisse->alis; ?> <span class="currency">TRY</span></div>
                      </li>
                      <li class="col-auto mb-1">
                        <div class="kanews-mgfsa14"><?php esc_html_e( 'Satış', 'kanews' ); ?></div>
                        <div class="kanews-mgfsa141"><?php echo $data->$hisse->satis; ?> <span class="currency">TRY</span></div>
                      </li>
                      </li>
                      <li class="col-auto">
                        <div class="kanews-mgfsa14"><?php esc_html_e( 'Değişim', 'kanews' ); ?></div>
                        <div class="kanews-mgfsa141"><?php echo $data->$hisse->degisim; ?><span class="currency">%</span></div>
                      </li>


                      <li class="col-auto">
                        <div class="kanews-mgfsa14"><?php esc_html_e( 'Son Güncelleme', 'kanews' ); ?></div>
                        <div class="kanews-mgfsa141"><?php echo $data->$hisse->tarih; ?></div>
                      </li>
                    </ul>
                  </div>

                </div>
              </div>


                    <a href="<?php the_permalink(); ?>" class="kanews-label mb-2"><?php _e('Diğer Hisselere Göz At', 'kanews'); ?></a>
            
            
              <div class="kanews-section" style="overflow:hidden">
       
                <!-- Period Selector -->
                <div class="d-flex flex-wrap align-items-center g-10 p-1">
                  <button class="kanews-label period-btn active" data-period="1"><?php _e('Gün İçi', 'kanews'); ?></button>
                  <button class="kanews-label period-btn" data-period="2"><?php _e('Hafta', 'kanews'); ?></button>
                  <button class="kanews-label period-btn" data-period="3"><?php _e('1 Ay', 'kanews'); ?></button>
                  <button class="kanews-label period-btn" data-period="4"><?php _e('6 Ay', 'kanews'); ?></button>
                  <button class="kanews-label period-btn" data-period="5"><?php _e('1 Yıl', 'kanews'); ?></button>
                  <button class="kanews-label period-btn" data-period="6"><?php _e('3 Yıl', 'kanews'); ?></button>
                  <button class="kanews-label period-btn" data-period="7"><?php _e('Tümü', 'kanews'); ?></button>
                </div>
                <hr class="hr-widget">
                
                <!-- Highcharts Container -->
                <div id="hisse-chart-container" style="width: 100%; height: 610px; min-width: 310px;"></div>
                
                <!-- Highcharts Scripts -->
                <script src="https://code.highcharts.com/stock/highstock.js"></script>
                <script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
                <script src="https://code.highcharts.com/stock/modules/accessibility.js"></script>
                <script type="text/javascript">
                (function() {
                  var hisseSymbol = '<?php echo esc_js($hisse); ?>';
                  var currentPeriod = 1;
                  var chart = null;
                  
                  // Generate unique callback name
                  var callbackCounter = 0;
                  function getCallbackName() {
                    return 'jQuery' + Date.now() + '_' + (callbackCounter++);
                  }
                  
                  // Fetch chart data from API
                  function fetchChartData(period) {
                    var url = 'https://uzmanpara.milliyet.com.tr/c/grafik_data_nocsv.asp?sembol=' + encodeURIComponent(hisseSymbol) + '&tur=' + period + '&tip=1&period=1&_=' + Date.now();
                    
                    // Try fetching without callback first (if CORS allows)
                    fetch(url)
                      .then(function(response) {
                        if (!response.ok) {
                          throw new Error('Network response was not ok');
                        }
                        return response.text();
                      })
                      .then(function(text) {
                        // Try to parse as JSON
                        try {
                          var data = JSON.parse(text);
                          if (data && data.length > 0) {
                            processChartData(data, period);
                            return;
                          }
                        } catch (e) {
                          // If not JSON, might be JSONP - try to extract data
                          var jsonpMatch = text.match(/^[^(]*\((\[.*\])\)/);
                          if (jsonpMatch) {
                            var data = JSON.parse(jsonpMatch[1]);
                            if (data && data.length > 0) {
                              processChartData(data, period);
                              return;
                            }
                          }
                        }
                        throw new Error('Could not parse response');
                      })
                      .catch(function(error) {
                        // Fallback to JSONP if fetch fails (CORS issue)
                        fetchChartDataJSONP(period);
                      });
                  }
                  
                  // Fallback JSONP method
                  function fetchChartDataJSONP(period) {
                    var callbackName = getCallbackName();
                    var url = 'https://uzmanpara.milliyet.com.tr/c/grafik_data_nocsv.asp?sembol=' + encodeURIComponent(hisseSymbol) + '&tur=' + period + '&tip=1&period=1';
                    
                    // Create script element for JSONP
                    var script = document.createElement('script');
                    script.src = url + '&callback=' + callbackName + '&_=' + Date.now();
                    
                    // Create global callback function
                    window[callbackName] = function(data) {
                      // Clean up
                      delete window[callbackName];
                      if (script.parentNode) {
                        script.parentNode.removeChild(script);
                      }
                      
                      if (data && data.length > 0) {
                        processChartData(data, period);
                      } else {
                        console.error('No data received');
                        if (chart) {
                          chart.showLoading('Veri alınamadı!');
                        }
                      }
                    };
                    
                    // Handle errors
                    script.onerror = function() {
                      delete window[callbackName];
                      if (script.parentNode) {
                        script.parentNode.removeChild(script);
                      }
                      if (chart) {
                        chart.showLoading('Veri yüklenirken hata oluştu');
                      }
                    };
                    
                    document.head.appendChild(script);
                  }
                  
                  // Process and display chart data
                  function processChartData(data, period) {
                    var ohlc = [];
                    var volume = [];
                    
                    // Sort data by date
                    data.sort(function(a, b) {
                      return new Date(a.tarih) - new Date(b.tarih);
                    });
                    
                    data.forEach(function(item) {
                      var timestamp = new Date(item.tarih).getTime();
                      ohlc.push([
                        timestamp,
                        parseFloat(item.acilis),
                        parseFloat(item.yuksek),
                        parseFloat(item.dusuk),
                        parseFloat(item.kapanis)
                      ]);
                      volume.push([
                        timestamp,
                        parseFloat(item.hacim)
                      ]);
                    });
                    
                    // Update or create chart
                    if (!chart) {
                      chart = Highcharts.stockChart('hisse-chart-container', {
                        chart: {
                          height: 610
                        },
                        rangeSelector: {
                          enabled: period === 1 ? false : true,
                          selected: period === 1 ? 0 : 1
                        },
                        title: {
                          text: hisseSymbol + ' - Hisse Senedi Grafiği'
                        },
                        xAxis: {
                          dateTimeLabelFormats: period === 1 ? {
                            millisecond: '%H:%M:%S',
                            second: '%H:%M:%S',
                            minute: '%H:%M',
                            hour: '%H:%M',
                            day: '%H:%M',
                            week: '%e %b',
                            month: '%b \'%y',
                            year: '%Y'
                          } : {
                            millisecond: '%H:%M:%S',
                            second: '%H:%M:%S',
                            minute: '%H:%M',
                            hour: '%H:%M',
                            day: '%e %b',
                            week: '%e %b',
                            month: '%b \'%y',
                            year: '%Y'
                          },
                          units: period === 1 ? [
                            ['minute', [5, 15, 30]],
                            ['hour', [1, 2, 4, 6, 12]]
                          ] : undefined
                        },
                        yAxis: [{
                          labels: {
                            align: 'right',
                            x: -3
                          },
                          title: {
                            text: 'Fiyat'
                          },
                          height: '60%',
                          lineWidth: 2
                        }, {
                          labels: {
                            align: 'right',
                            x: -3
                          },
                          title: {
                            text: 'Hacim'
                          },
                          top: '65%',
                          height: '35%',
                          offset: 0,
                          lineWidth: 2
                        }],
                        tooltip: {
                          split: true,
                          formatter: function() {
                            var points = this.points || [this.point];
                            var dateFormat = period === 1 ? '%H:%M - %e %b %Y' : '%A, %e %b %Y';
                            var tooltip = '<b>' + Highcharts.dateFormat(dateFormat, points[0].x) + '</b><br/>';
                            points.forEach(function(point) {
                              if (point.series.name === 'Hacim') {
                                tooltip += '<span style="color:' + point.color + '">\u25CF</span> ' + point.series.name + ': <b>' + Highcharts.numberFormat(point.y, 0) + '</b><br/>';
                              } else {
                                // Candlestick tooltip
                                if (point.open !== undefined) {
                                  tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Açılış: <b>' + Highcharts.numberFormat(point.open, 2) + ' TRY</b><br/>';
                                  tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Yüksek: <b>' + Highcharts.numberFormat(point.high, 2) + ' TRY</b><br/>';
                                  tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Düşük: <b>' + Highcharts.numberFormat(point.low, 2) + ' TRY</b><br/>';
                                  tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Kapanış: <b>' + Highcharts.numberFormat(point.close, 2) + ' TRY</b><br/>';
                                } else {
                                  tooltip += '<span style="color:' + point.color + '">\u25CF</span> ' + point.series.name + ': <b>' + Highcharts.numberFormat(point.y, 2) + ' TRY</b><br/>';
                                }
                              }
                            });
                            return tooltip;
                          }
                        },
                        series: [{
                          type: 'candlestick',
                          name: hisseSymbol,
                          data: ohlc,
                          id: 'primary',
                          upColor: '#26a69a', // Yeşil - yükseliş
                          color: '#ef5350',  // Kırmızı - düşüş
                          lineColor: '#26a69a',
                          upLineColor: '#26a69a'
                        }, {
                          type: 'column',
                          name: 'Hacim',
                          data: volume,
                          yAxis: 1,
                          color: '#90EE90'
                        }],
                        navigator: {
                          enabled: period === 1 ? false : true
                        },
                        scrollbar: {
                          enabled: period === 1 ? false : true
                        },
                        credits: {
                          enabled: false
                        },
                        lang: {
                          loading: 'Yükleniyor...',
                          months: ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'],
                          weekdays: ['Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi'],
                          shortMonths: ['Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara'],
                          rangeSelectorFrom: 'Başlangıç',
                          rangeSelectorTo: 'Bitiş',
                          rangeSelectorZoom: 'Yakınlaştır',
                          downloadPNG: 'PNG olarak indir',
                          downloadJPEG: 'JPEG olarak indir',
                          downloadPDF: 'PDF olarak indir',
                          downloadSVG: 'SVG olarak indir',
                          printChart: 'Grafiği yazdır',
                          resetZoom: 'Yakınlaştırmayı sıfırla',
                          resetZoomTitle: 'Yakınlaştırmayı sıfırla'
                        }
                      });
                    } else {
                      // Update existing chart
                      chart.series[0].setData(ohlc, true);
                      chart.series[1].setData(volume, true);
                      chart.update({
                        rangeSelector: {
                          enabled: period === 1 ? false : true
                        },
                        navigator: {
                          enabled: period === 1 ? false : true
                        },
                        scrollbar: {
                          enabled: period === 1 ? false : true
                        },
                        xAxis: {
                          dateTimeLabelFormats: period === 1 ? {
                            millisecond: '%H:%M:%S',
                            second: '%H:%M:%S',
                            minute: '%H:%M',
                            hour: '%H:%M',
                            day: '%H:%M',
                            week: '%e %b',
                            month: '%b \'%y',
                            year: '%Y'
                          } : {
                            millisecond: '%H:%M:%S',
                            second: '%H:%M:%S',
                            minute: '%H:%M',
                            hour: '%H:%M',
                            day: '%e %b',
                            week: '%e %b',
                            month: '%b \'%y',
                            year: '%Y'
                          },
                          units: period === 1 ? [
                            ['minute', [5, 15, 30]],
                            ['hour', [1, 2, 4, 6, 12]]
                          ] : undefined
                        },
                        tooltip: {
                          formatter: function() {
                            var points = this.points || [this.point];
                            var dateFormat = period === 1 ? '%H:%M - %e %b %Y' : '%A, %e %b %Y';
                            var tooltip = '<b>' + Highcharts.dateFormat(dateFormat, points[0].x) + '</b><br/>';
                            points.forEach(function(point) {
                              if (point.series.name === 'Hacim') {
                                tooltip += '<span style="color:' + point.color + '">\u25CF</span> ' + point.series.name + ': <b>' + Highcharts.numberFormat(point.y, 0) + '</b><br/>';
                              } else {
                                // Candlestick tooltip
                                if (point.open !== undefined) {
                                  tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Açılış: <b>' + Highcharts.numberFormat(point.open, 2) + ' TRY</b><br/>';
                                  tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Yüksek: <b>' + Highcharts.numberFormat(point.high, 2) + ' TRY</b><br/>';
                                  tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Düşük: <b>' + Highcharts.numberFormat(point.low, 2) + ' TRY</b><br/>';
                                  tooltip += '<span style="color:' + (point.close >= point.open ? '#26a69a' : '#ef5350') + '">\u25CF</span> Kapanış: <b>' + Highcharts.numberFormat(point.close, 2) + ' TRY</b><br/>';
                                } else {
                                  tooltip += '<span style="color:' + point.color + '">\u25CF</span> ' + point.series.name + ': <b>' + Highcharts.numberFormat(point.y, 2) + ' TRY</b><br/>';
                                }
                              }
                            });
                            return tooltip;
                          }
                        }
                      });
                    }
                    
                    chart.hideLoading();
                  }
                  
                  // Period button click handlers
                  document.addEventListener('DOMContentLoaded', function() {
                    var periodButtons = document.querySelectorAll('.period-btn');
                    periodButtons.forEach(function(btn) {
                      btn.addEventListener('click', function() {
                        // Update active state
                        periodButtons.forEach(function(b) {
                          b.classList.remove('active');
                        });
                        this.classList.add('active');
                        
                        // Get new period
                        var newPeriod = parseInt(this.getAttribute('data-period'));
                        if (newPeriod !== currentPeriod) {
                          currentPeriod = newPeriod;
                          if (chart) {
                            chart.showLoading('Veri yükleniyor...');
                          }
                          fetchChartData(newPeriod);
                        }
                      });
                    });
                    
                    // Load initial data
                    if (chart) {
                      chart.showLoading('Veri yükleniyor...');
                    }
                    fetchChartData(currentPeriod);
                  });
                })();
                </script>
              </div>

              <div class="kanews-section">
                <!-- TradingView Widget BEGIN -->
                <div class="tradingview-widget-container">
                  <div class="tradingview-widget-container__widget"></div>
                  <div class="tradingview-widget-copyright"><a href="https://tr.tradingview.com/" rel="noopener nofollow" target="_blank"><span class="blue-text">Tüm piyasaları TradingView üzerinden takip edin</span></a></div>
                  <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-financials.js" async>
                  {
                    "colorTheme": "light",
                    "isTransparent": false,
                    "largeChartUrl": "<?php the_permalink(); ?>?hisse={tvsymbol}",
                    "displayMode": "regular",
                    "width": "100%",
                    "height": "625",
                    "symbol": "BIST:<?php echo $hisse; ?>",
                    "locale": "tr"
                  }
                  </script>
                </div>
                <!-- TradingView Widget END -->
              </div>
        
              <?php get_template_part('template-parts/content/components/related', 'page2', array( 
                'posts_per_page' => 10,
                's' => $hisse 
              ) ); ?>

            </div>

            <script>
              document.getElementsByTagName('title')[0].innerHTML = "<?php echo $new_title; ?>";
              document.getElementsByTagName('meta')["description"].content = "<?php echo $page_desc; ?>";
            </script>
          <?php endif; ?>

        <?php else: ?>
          <div class="col-12"><?php echo kanews_private_content('a'); ?></div>
        <?php endif; ?>

      </div>
    </div>
  </main>
<?php get_footer();
