<?php
/**
 * Template Name: Nöbetçi Eczaneler
 * @theme kanews
 * @developer kanthemes.com
 */
__( 'Nöbetçi Eczaneler', 'kanews' );
defined( 'ABSPATH' ) || exit; // Exit if accessed directly

$region = (isset($_GET['sehir']) &&  $_GET['sehir'] != 'null' && !empty($_GET['sehir'])) ? ucwords($_GET['sehir']) : kanews_get_option('eczane-page-city', 'Ankara');
$city = (isset($_GET['ilce']) && $_GET['ilce'] != 'null' && !empty($_GET['ilce'])) ? ucwords($_GET['ilce']) : kanews_get_option('eczane-page-city2');
if(empty(kanews_get_option('eczane-page-city2')) && !isset($_GET['ilce']) )
$city = '';

$new_region = $region;
if( empty($city) )
$city = $region;


$date = date('Y-m-d');

$data = kanews_eczane_times_api( $region, $city );

// Get the updated date from the data
$updated_date = '';
if (isset($data['updated']) && !empty($data['updated'])) {
  $updated_date = $data['updated'];
}

$response = get_local_file_contents(KAN_TEMPLATE_PATH."/inc/api/turkiye.json");
$data2 = json_decode($response, true);
if( isset($data2['status']) && $data2['status'] == 'OK' ) { 
  foreach(  $data2['data'] as $key => $value ) {
    if( kanews_seflink($value['name']) == kanews_seflink($region)  ) {
      $new_region = $value['name'];
      break;
    }
  }
}

$plaka = kanews_get_plaka($new_region)-1;

// Check if there's no data or no pharmacy data - return 404
if( empty($data['data']) || $data['data'] == 'error' || (isset($data['data'][0]) && empty($data['data'][0])) ) {
  nocache_headers();
  include( get_query_template( '404' ) );
  die();
} else {
  if( $city != '' && $region != $city ) {
  $title = wp_sprintf( esc_html__('%1$s Nöbetçi Eczaneler - %2$s', 'kanews'), $city, $new_region );
  $new_title = $title.' - '.get_bloginfo( 'name' );
  } else {
  $title = wp_sprintf( esc_html__('%1$s Nöbetçi Eczaneler', 'kanews'), $new_region );
  $new_title = $title.' - '.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 );
}


get_header(); ?>

  <?php while ( have_posts() ) : the_post(); ?>
    <div class="kanews-page-header">
      <div class="container">
        <div class="row align-items-center justify-space-between mb-1">
          <div class="col">
            <h1 class="kanews-page-title"><img style="vertical-align: -4px;" src="<?php echo get_template_directory_uri(  ); ?>/assets/img/static/eczane.jpg" loading="lazy" width="32" height="32" alt="e"> <?php echo $title; ?></h1>
          </div>
          <div class="col-auto">
            <?php 
            $out = '';
            if( isset($data2['status']) && $data2['status'] == 'OK' ) {
            echo '<div class="kanews-btn kanews-btn-light m-0" data-toggle="kanews-city-search">'.$new_region.' <i class="icon-caret icon-180deg"></i></div>';
              $out .= '<div id="kanews-city-search" class="kanews-search-cities kanews-scroll">';
              $out .= '<input placeholder="'.esc_html__( 'Şehir ara', 'kanews' ).'" id="kanews-search-input" />';
            
                foreach( $data2['data'] as $key => $value ) {
                  $query_args = array('sehir' => kanews_seflink($value['name']));
                  $out .= '<a href="'.esc_url( add_query_arg( $query_args, get_permalink() ) ).'" class="kanews-search-city" data-city="'.esc_attr($value['name']).'">'.$value['name'].'</a>';
                }
                $out .= '</div>';
                echo $out;
              }
              ?>
          </div>
        </div>
        <div class="row">
          <div class="col-12">
            <div id="ilceler" class="kanews-label-group">
              <?php 
              if( isset($data2['status']) && $data2['status'] == 'OK' ) {
                $query_args = array('sehir' => kanews_seflink($data2['data'][$plaka]['name']));
                echo '<a class="kanews-label active" href="'.esc_url( add_query_arg( $query_args, get_permalink() ) ).'">'.esc_html__( 'Tümü', 'kanews' ).'</a>';

                foreach($data2['data'][$plaka]['districts'] as $key => $value) {
                  echo '<a class="kanews-label color-dark" href="'.esc_url( add_query_arg( array('sehir' => kanews_seflink($data2['data'][$plaka]['name']), 'ilce' => kanews_seflink($value['name'])), get_permalink() ) ).'">'.$value['name'].'</a>';
                }
              }
              ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  <?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 mb-1">
            <?php if (isset($data['detay']['description']) && !empty($data['detay']['description'])): ?>
              <div class="kanews-response kanews-response-info">
                <?php echo $data['detay']['description']; ?>
              </div>
            <?php endif; ?>
            <?php
            if ( isset($data['data']) && !empty($data['data'][0]) && $data['data'] != 'error') {
              echo '<div class="row equal-height">';
              
              // Count valid pharmacies
              $valid_pharmacy_count = 0;
              foreach( $data['data'][0] as $key => $eczane) {
                if( !empty($eczane['eczane_adi']) ) {
                  $valid_pharmacy_count++;
                }
              }
              
              // If no valid pharmacies found, return 404
              if( $valid_pharmacy_count == 0 ) {
                nocache_headers();
                include( get_query_template( '404' ) );
                die();
              }
              
              foreach( $data['data'][0] as $key => $eczane) {
                if( !empty($eczane['eczane_adi']) ) {
                echo '<div class="col-12 col-md-6 col-lg-4"><div class="pharmacy-item">';
                  echo '<div><div class="pharmacy-name"><img src="'.get_template_directory_uri(  ).'/assets/img/static/eczane.jpg" loading="lazy" width="24" height="24" alt="e">'.$eczane['eczane_adi'].'</div>';
                  echo '<div class="pharmacy-adress">'.$eczane['adres'].'</div></div>';
                  if (strpos($eczane['adres'], 'my-2') !== false)
                  
                  echo '</div>';
                  echo '<small class="pharmacy-notice color-success mt-1">'.$eczane['important'].'</small>';
                  echo '<div><div class="pharmacy-tel"><a class="kanews-btn mb-0 bg-dark kanews-btn-sm kanews-btn-block" href="tel:' . preg_replace('/\D/', '', $eczane['telefon']) . '" class="pharmacy-phone">'.esc_html( 'Telefon Et', 'kanews' ).': '.$eczane['telefon'].'</a></div>';
                  echo '<div class="pharmacy-maps"><a class="kanews-btn kanews-btn-block kanews-btn-sm" target="_blank" rel="nofollow" href="https://maps.google.com/?q='.urlencode($eczane['adres']).'" class="pharmacy-value">'.esc_html__( 'Yol tarifi', 'kanews' ).'</a></div></div>';
                echo '</div></div>';
                } elseif($key == 'notice') {
                  echo '<div class="kanews-response kanews-response-dark" role="alert">'.$eczane.'</div>';
                } else {
                  echo '<div class="kanews-response kanews-response-info" role="alert">'.sprintf( esc_html__('%s için %s/%s bölgesinde nöbetçi eczane kaydı bulunamadı. ', 'kanews'), $date, $new_region, $city  ).'</div>';
                }
              }
            } else {
              echo '<div class="kanews-response kanews-response-info" role="alert">'.sprintf( esc_html__('%s için %s/%s bölgesinde nöbetçi eczane kaydı bulunamadı. ', 'kanews'), $date, $new_region, $city  ).'</div>';
            }
            ?>
          
          </div>

          <?php get_template_part('template-parts/content/components/related', 'page'); ?>
          
          <?php while ( have_posts() ) : the_post(); 
            if ($post->post_content): ?>
  
                <div class="kanews-article kanews-section-flat kanews-article-1">
                  <div class="kanews-article-content entry-content">
                    <?php the_content(); ?>
                  </div>
                </div>
           
            <?php endif; ?>
          <?php endwhile; ?>
        <?php else: ?>
          <?php echo kanews_private_content('a'); ?>
        <?php endif; ?>

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