<?php
/**
 * Template Name: Gazete Manşetleri
 * @theme kanews
 * @developer kanthemes.com
 */
defined( 'ABSPATH' ) || exit; // Exit if accessed directly

// Set timezone
date_default_timezone_set( 'Europe/Istanbul' );

// Get current date
$day = (int) date( 'n' );
$gazetetarih = date( 'd' . ( $day < 10 ? '0' : '' ) . $day . 'y' );

// Format date for display
$today = kanews_get_turkish_date();

// Get custom newspapers from options
$custom_news = kanews_get_option( 'newspapers', [] );

$transient_name = 'kanews_np_data';
// Check if we need to update the newspaper data
$last_update = get_transient( $transient_name );
$today_date = date( 'Y-m-d' );
$need_update = ( $last_update !== $today_date );

if ( $need_update ) {
	set_transient( $transient_name, $today_date, DAY_IN_SECONDS );
}

// Get newspaper data from transient or fetch new data
$newspaper_data = get_transient( 'kanews_newspaper_data' );
if ( $newspaper_data === false || $need_update ) {
	$newspaper_data = kanews_fetch_newspaper_data( $today );
	// Store in transient for 24 hours
	set_transient( 'kanews_newspaper_data', $newspaper_data, DAY_IN_SECONDS );
}

// Add custom newspapers if any
if ( ! empty( $custom_news ) ) {
	foreach ( $custom_news as $key => $value ) {
		$slug = strtolower( urlencode( $value['title'] ) );
		$newspaper_name = kanews_capitalize_first_letter( $value['title'] );
		
		$newspaper_data[ $slug ] = [
			'name'                  => $newspaper_name,
			'date'                  => $today,
			'small_image'           => $value['media'],
			'large_image'           => $value['media'],
			'highest_quality_image' => $value['media'],
			'link'                  => '',
		];
	}
}

// Create newspapers array from newspaper_data
$newspapers = [];
foreach ( $newspaper_data as $key => $value ) {
	$newspapers[ $key ] = $value['name'];
}

// Check if a specific newspaper is requested
$read = isset( $_GET['gazete'] ) ? strtolower( urlencode( sanitize_text_field( wp_unslash( $_GET['gazete'] ) ) ) ) : null;
if ( $read !== null && ! isset( $newspapers[ $read ] ) ) {
	wp_safe_redirect( get_the_permalink(), 301 );
	exit;
}

// Set page title
$title = '';
$new_title = '';
if ( $read !== null && ! empty( $newspapers[ $read ] ) ) {
	$title = wp_sprintf( 
		esc_html__( '%1$s Gazetesi %2$s Günü Gazete Manşetleri', 'kanews' ), 
		$newspapers[ $read ], 
		$today 
	);
	$new_title = ucwords( $title ) . ' - ' . get_bloginfo( 'name' );
}

// Filter for custom title
function generate_custom_title( $title ) {
	global $new_title;
	if ( ! empty( $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
get_header(); 

// Page header
while ( have_posts() ) :
	the_post();
	$desc = isset( $newspapers[ $read ] ) 
		? wp_sprintf( 
			__( '%1$s gazetesinin %2$s tarihli gazete manşetlerine göz atın, en son gelişmeler ve öne çıkan haberlerle Türkiye\'nin gündemini takip edin!', 'kanews' ), 
			$newspapers[ $read ], 
			$today 
		) 
		: '';
	kanews_page_header( $post->ID, $title, '', $desc );
endwhile;

// Header ad
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 col-lg-2 kanews-sticky">
            <div class="kanews-section widget widget_pages kanews-collapse-wrapper">
              <?php echo kanews_widget_title( esc_html__( 'Gazeteler', 'kanews' ), 'div' ); ?>
            <ul>
              <li class="page_item <?php echo ( $read === null ) ? 'current_page_item' : ''; ?>">
                <a href="<?php the_permalink(); ?>"><?php esc_html_e( 'Hepsi', 'kanews' ); ?></a>
              </li>
              <?php 
              $counter = 0;
              foreach ( $newspapers as $key => $newspaper ) {
                $counter++;
                $collapse = $counter > 3 ? 'kanews-collapse-item hidden-mobile' : '';
                $is_current = ( $key === $read ) ? 'current_page_item' : '';
                ?>
                <li class="page_item <?php echo esc_attr( $is_current . ' ' . $collapse ); ?>">
                  <a href="<?php echo esc_url( add_query_arg( 'gazete', $key, get_the_permalink() ) ); ?>">
                    <?php echo esc_html( $newspaper ); ?>
                  </a>
                </li>
              <?php } ?>
            </ul>
            <div class="kanews-collapse-btn hidden-desktop">
              <i class="icon-arrow icon-3x"></i> 
              <span><?php esc_html_e( 'Daha Fazla Göster', 'kanews' ); ?></span>
            </div>
            </div>
          </div>
          
          <div class="col-12 col-md-9 col-lg-10">
                    <div class="post-width newspapers">
          <div class="row">
                            <?php if ( $read !== null ) : ?>
          <?php 
                                // Display single newspaper
                                if ( isset( $newspaper_data[ $read ] ) ) :
                                    $newspaper = $newspaper_data[ $read ];
                                    $share_url = get_permalink() . '?gazete=' . $read;
                                ?>
                                <div class="col-12">
                                    <div class="kanews-section newspaper-item">
                                        <a href="#" class="newspaper-zoom" data-image="<?php echo esc_url( $newspaper['highest_quality_image'] ); ?>" data-title="<?php echo esc_attr( $newspaper['name'] ); ?>">
                                            <?php echo kanews_widget_title( sprintf( esc_html__( '%s Gazetesi %s Günü 1. Sayfası', 'kanews' ), $newspaper['name'], $today ), 'h3' ); ?>
                                            <div class="kanews-table-date"><?php echo esc_html( $newspaper['date'] ); ?></div>
                                            <img src="<?php echo esc_url( $newspaper['highest_quality_image'] ); ?>" alt="<?php echo esc_attr( $newspaper['name'] ); ?>" loading="lazy">
                                        </a>
                                        <?php echo kanews_get_social_share_buttons( $share_url, $newspaper['name'] . ' Manşeti' ); ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                  <?php else : ?>
                                <?php 
                                // Display all newspapers in grid
                                foreach ( $newspaper_data as $key => $newspaper ) :
                                    $share_url = get_permalink() . '?gazete=' . $key;
                                    $image_url = ( ! empty( $newspaper['small_image'] ) && $newspaper['small_image'] !== 'https://s.gazeteoku.com/assets/web/files/blank.png' )
                                        ? $newspaper['small_image']
                                        : $newspaper['highest_quality_image'];
                                ?>
                                <div class="col-12 col-md-6 col-xl-4 col-lg-6">
                                    <div class="kanews-section newspaper-item">
                                        <a href="<?php echo esc_url( add_query_arg( 'gazete', $key, get_the_permalink() ) ); ?>" title="<?php echo esc_attr( $newspaper['name'] ); ?>">
                                            <?php echo kanews_widget_title( esc_html( $newspaper['name'] ), 'h2' ); ?>
                                            <div class="kanews-table-date"><?php echo esc_html( $newspaper['date'] ); ?></div>
                                            <img src="<?php echo esc_url( $image_url ); ?>" loading="lazy" alt="<?php echo esc_attr( $newspaper['name'] ); ?>">
                                        </a>
                                        <?php echo kanews_get_social_share_buttons( $share_url, $newspaper['name'] . ' Manşeti' ); ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
            <?php endif; ?>
                        </div>
                    </div>

          <?php 
          while ( have_posts() ) :
            the_post();
            if ( ! empty( $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; ?>
                </div>
        <?php else : ?>
          <div class="col-12"><?php echo kanews_private_content( 'a' ); ?></div>
        <?php endif; ?>
      </div>
    </div>
  </main>

<!-- Modal for zoomed newspaper -->
<div id="newspaperModal" class="modal">
    <span class="modal-close">&times;</span>
    <img class="modal-content" id="modalImage">
    <div id="modalCaption"></div>
</div>

<!-- Add JavaScript for zoom functionality -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Get the modal
    var modal = document.getElementById("newspaperModal");
    var modalImg = document.getElementById("modalImage");
    var captionText = document.getElementById("modalCaption");
    var closeBtn = document.getElementsByClassName("modal-close")[0];
    
    // Add click event to all newspaper images
    var newspaperLinks = document.querySelectorAll('.newspaper-zoom');
    newspaperLinks.forEach(function(link) {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            var imgSrc = this.getAttribute('data-image');
            var imgTitle = this.getAttribute('data-title');
            
            modal.style.display = "block";
            modalImg.src = imgSrc;
            captionText.innerHTML = imgTitle;
        });
    });
    
    // Close modal when clicking the close button
    closeBtn.onclick = function() {
        modal.style.display = "none";
    }
    
    // Close modal when clicking outside the image
    modal.onclick = function(e) {
        if (e.target === modal) {
            modal.style.display = "none";
        }
    }
    
    // Initialize tooltips if Bootstrap is available
    if (typeof $ !== 'undefined' && $.fn.tooltip) {
        $('[data-toggle="tooltip"]').tooltip();
    }
});
</script>

<?php
/**
 * Get Turkish formatted date
 *
 * @return string Formatted date
 */
function kanews_get_turkish_date() {
	if ( class_exists( 'IntlDateFormatter' ) ) {
		$formatter = new IntlDateFormatter( 'tr_TR', IntlDateFormatter::LONG, IntlDateFormatter::NONE );
		return $formatter->format( time() );
	}

	// Fallback using DateTime
	$date = new DateTime();
	$date->setTimezone( new DateTimeZone( 'Europe/Istanbul' ) );
	
	$day_num = $date->format( 'j' );
	$month_num = (int) $date->format( 'n' );
	$year_num = $date->format( 'Y' );
	$weekday_num = (int) $date->format( 'w' ); // 0 (Sunday) to 6 (Saturday)
	
	// Turkish month names
	$months = [ '', 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık' ];
	// Turkish weekday names
	$weekdays = [ 'Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi' ];
	
	return $day_num . ' ' . $months[ $month_num ] . ' ' . $year_num . ', ' . $weekdays[ $weekday_num ];
}

/**
 * Capitalize first letter of string
 *
 * @param string $string Input string
 * @return string Capitalized string
 */
function kanews_capitalize_first_letter( $string ) {
	if ( empty( $string ) ) {
		return '';
	}
	
	$string = mb_strtolower( $string, 'UTF-8' );
	$string = str_replace( 'i̇', 'i', $string ); // Replace İ with i
	$first_char = mb_substr( $string, 0, 1, 'UTF-8' );
	$first_char_upper = mb_strtoupper( $first_char, 'UTF-8' );
	
	// If uppercase is İ, convert to I
	if ( $first_char_upper === 'İ' ) {
		$first_char_upper = 'I';
	}
	
	return $first_char_upper . mb_substr( $string, 1, null, 'UTF-8' );
}

/**
 * Fetch newspaper data from external source
 *
 * @param string $today Today's date
 * @return array Newspaper data
 */
function kanews_fetch_newspaper_data( $today ) {
	$newspaper_data = [];
	
	// Fetch newspaper data from gazeteoku.com
	$source_url = 'https://www.gazeteoku.com/gazeteler';
	$response = wp_remote_get( $source_url );
	
	if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ) {
		return $newspaper_data;
	}
	
	$html = wp_remote_retrieve_body( $response );
	
	// Use DOMDocument to parse the HTML
	$dom = new DOMDocument();
	@$dom->loadHTML( mb_convert_encoding( $html, 'HTML-ENTITIES', 'UTF-8' ) );
	$xpath = new DOMXPath( $dom );
	
	// Find all newspaper items
	$newspaper_items = $xpath->query( '//div[contains(@class, "col-12 col-md-6 col-xl-4 col-lg-6")]' );
	
	foreach ( $newspaper_items as $item ) {
		// Extract newspaper name
		$name_element = $xpath->query( './/strong', $item )->item( 0 );
		$name = $name_element ? trim( $name_element->textContent ) : '';
		
		if ( empty( $name ) ) {
			continue;
		}
		
		$name = kanews_capitalize_first_letter( $name );
		
		// Extract date
		$date_element = $xpath->query( './/small', $item )->item( 0 );
		$date = $date_element ? trim( $date_element->textContent ) : $today;
		
		// Extract image URL
		$img_element = $xpath->query( './/img', $item )->item( 0 );
		$small_image = $img_element ? $img_element->getAttribute( 'src' ) : '';
		$large_image = $img_element ? $img_element->getAttribute( 'data-srcset' ) : '';
		
		// Fix blank image issue
		if ( empty( $small_image ) || $small_image === 'https://s.gazeteoku.com/assets/web/files/blank.png' ) {
			$small_image = $img_element ? $img_element->getAttribute( 'data-src' ) : '';
			
			if ( empty( $small_image ) && ! empty( $large_image ) ) {
				preg_match( '/^(.*?)\s/', $large_image, $matches );
				if ( ! empty( $matches[1] ) ) {
					$small_image = $matches[1];
				}
			}
		}
		
		// Fix large image URL format
		if ( ! empty( $large_image ) ) {
			preg_match( '/^(.*?)\s/', $large_image, $matches );
			if ( ! empty( $matches[1] ) ) {
				$large_image = $matches[1];
			}
		}
		
		// Get the highest quality image URL
		$highest_quality_image = kanews_get_highest_quality_image( $large_image, $small_image );
		
		// Extract link
		$link_element = $xpath->query( './/a', $item )->item( 0 );
		$link = $link_element ? $link_element->getAttribute( 'href' ) : '';
		
		// Create slug from name
		$slug = sanitize_title( $name );
		
		if ( ! empty( $small_image ) ) {
			$newspaper_data[ $slug ] = [
				'name'                  => $name,
				'date'                  => $date,
				'small_image'           => $small_image,
				'large_image'           => $large_image,
				'highest_quality_image' => $highest_quality_image,
				'link'                  => $link,
			];
		}
	}
	
	return $newspaper_data;
}

/**
 * Get highest quality image URL
 *
 * @param string $large_image Large image URL
 * @param string $small_image Small image URL
 * @return string Highest quality image URL
 */
function kanews_get_highest_quality_image( $large_image, $small_image ) {
	$highest_quality_image = '';
	
	if ( ! empty( $large_image ) ) {
		// Check if the URL contains a size indicator (like /3/460/772/)
		if ( preg_match( '/\/\d+\/\d+\/\d+\//', $large_image ) ) {
			$highest_quality_image = preg_replace( '/\/\d+\/\d+\/\d+\//', '/', $large_image );
		} else {
			$highest_quality_image = $large_image;
		}
		
		// Ensure the URL has the correct directory structure (year/month/day)
		if ( str_contains( $highest_quality_image, '/storage/files/images/' ) ) {
			$highest_quality_image = kanews_fix_image_url_structure( $highest_quality_image );
		}
	} elseif ( ! empty( $small_image ) ) {
		$highest_quality_image = $small_image;
		
		// Apply the same directory structure fix to small_image if needed
		if ( str_contains( $highest_quality_image, '/storage/files/images/' ) ) {
			$highest_quality_image = kanews_fix_image_url_structure( $highest_quality_image );
		}
	}
	
	return $highest_quality_image;
}

/**
 * Fix image URL directory structure
 *
 * @param string $url Image URL
 * @return string Fixed URL
 */
function kanews_fix_image_url_structure( $url ) {
	// Check if the URL already has the year/month/day structure
	if ( preg_match( '/\/\d{4}\/\d{2}\/\d{2}\//', $url ) ) {
		return $url;
	}
	
	// Extract the filename part
	$filename = basename( $url );
	
	// Extract date from the filename if possible (format: newspaper-YYYY-MM-DD-xxxx.jpg)
	if ( preg_match( '/(\d{4})-(\d{2})-(\d{2})/', $filename, $date_matches ) ) {
		$year = $date_matches[1];
		$month = $date_matches[2];
		$day = $date_matches[3];
		
		// Reconstruct the URL with the correct directory structure
		return preg_replace( '/\/storage\/files\/images\//', "/storage/files/images/{$year}/{$month}/{$day}/", $url );
	}
	
	return $url;
}

/**
 * Get social share buttons HTML
 *
 * @param string $url Share URL
 * @param string $text Share text
 * @return string HTML output
 */
function kanews_get_social_share_buttons( $url, $text ) {
	$encoded_url = urlencode( $url );
	$encoded_text = urlencode( $text );
	
	ob_start();
	?>
	<div class="d-flex flex-wrap align-items-center justify-content-center p-1" style="gap: 1rem">
		<a href="https://www.facebook.com/share.php?u=<?php echo esc_attr( $encoded_url ); ?>" class="facebook" data-toggle="tooltip" data-placement="right" title="<?php echo esc_attr__( 'Facebook\'da paylaş', 'kanews' ); ?>">
			<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 32 32">
				<path d="M19 6h5v-6h-5c-3.86 0-7 3.14-7 7v3h-4v6h4v16h6v-16h5l1-6h-6v-3c0-0.542 0.458-1 1-1z"></path>
			</svg>
		</a>
		<a href="https://twitter.com/share?url=<?php echo esc_attr( $encoded_url ); ?>&text=<?php echo esc_attr( $encoded_text ); ?>" class="twitter" data-toggle="tooltip" data-placement="right" title="<?php echo esc_attr__( 'Twitter\'da paylaş', 'kanews' ); ?>">
			<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 32 32">
				<path d="M32 7.075c-1.175 0.525-2.444 0.875-3.769 1.031 1.356-0.813 2.394-2.1 2.887-3.631-1.269 0.75-2.675 1.3-4.169 1.594-1.2-1.275-2.906-2.069-4.794-2.069-3.625 0-6.563 2.938-6.563 6.563 0 0.512 0.056 1.012 0.169 1.494-5.456-0.275-10.294-2.888-13.531-6.862-0.563 0.969-0.887 2.1-0.887 3.3 0 2.275 1.156 4.287 2.919 5.463-1.075-0.031-2.087-0.331-2.975-0.819 0 0.025 0 0.056 0 0.081 0 3.181 2.263 5.838 5.269 6.437-0.55 0.15-1.131 0.231-1.731 0.231-0.425 0-0.831-0.044-1.237-0.119 0.838 2.606 3.263 4.506 6.131 4.563-2.25 1.762-5.075 2.813-8.156 2.813-0.531 0-1.050-0.031-1.569-0.094 2.913 1.869 6.362 2.95 10.069 2.95 12.075 0 18.681-10.006 18.681-18.681 0-0.287-0.006-0.569-0.019-0.85 1.281-0.919 2.394-2.075 3.275-3.394z"></path>
			</svg>
		</a>
		<a href="https://pinterest.com/pin/create/button/?url=<?php echo esc_attr( $encoded_url ); ?>&description=<?php echo esc_attr( $encoded_text ); ?>" class="pinterest" data-toggle="tooltip" data-placement="right" title="<?php echo esc_attr__( 'Pinterest\'e ekle', 'kanews' ); ?>">
			<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 32 32">
				<path d="M16 0c-8.825 0-16 7.175-16 16s7.175 16 16 16 16-7.175 16-16-7.175-16-16-16zM16 29.863c-1.431 0-2.806-0.219-4.106-0.619 0.563-0.919 1.412-2.431 1.725-3.631 0.169-0.65 0.863-3.294 0.863-3.294 0.45 0.863 1.775 1.594 3.175 1.594 4.181 0 7.194-3.844 7.194-8.625 0-4.581-3.738-8.006-8.544-8.006-5.981 0-9.156 4.019-9.156 8.387 0 2.031 1.081 4.563 2.813 5.369 0.262 0.125 0.4 0.069 0.463-0.188 0.044-0.194 0.281-1.131 0.387-1.575 0.031-0.137 0.019-0.262-0.094-0.4-0.575-0.694-1.031-1.975-1.031-3.162 0-3.056 2.313-6.019 6.256-6.019 3.406 0 5.788 2.319 5.788 5.637 0 3.75-1.894 6.35-4.356 6.35-1.363 0-2.381-1.125-2.050-2.506 0.394-1.65 1.15-3.425 1.15-4.613 0-1.063-0.569-1.95-1.756-1.95-1.394 0-2.506 1.438-2.506 3.369 0 1.225 0.412 2.056 0.412 2.056s-1.375 5.806-1.625 6.887c-0.281 1.2-0.169 2.881-0.050 3.975-5.156-2.012-8.813-7.025-8.813-12.9 0-7.656 6.206-13.863 13.862-13.863s13.863 6.206 13.863 13.863c0 7.656-6.206 13.863-13.863 13.863z"></path>
			</svg>
		</a>
		<a href="whatsapp://send?text=<?php echo esc_attr( $encoded_text . ' - ' . $encoded_url ); ?>" class="whatsapp" data-toggle="tooltip" data-placement="right" title="<?php echo esc_attr__( 'WhatsApp\'da paylaş', 'kanews' ); ?>">
			<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 32 32">
				<path d="M27.281 4.65c-2.994-3-6.975-4.65-11.219-4.65-8.738 0-15.85 7.112-15.85 15.856 0 2.794 0.731 5.525 2.119 7.925l-2.25 8.219 8.406-2.206c2.319 1.262 4.925 1.931 7.575 1.931h0.006c0 0 0 0 0 0 8.738 0 15.856-7.113 15.856-15.856 0-4.238-1.65-8.219-4.644-11.219zM16.069 29.050v0c-2.369 0-4.688-0.637-6.713-1.837l-0.481-0.288-4.987 1.306 1.331-4.863-0.313-0.5c-1.325-2.094-2.019-4.519-2.019-7.012 0-7.269 5.912-13.181 13.188-13.181 3.519 0 6.831 1.375 9.319 3.862 2.488 2.494 3.856 5.8 3.856 9.325-0.006 7.275-5.919 13.188-13.181 13.188zM23.294 19.175c-0.394-0.2-2.344-1.156-2.706-1.288s-0.625-0.2-0.894 0.2c-0.262 0.394-1.025 1.288-1.256 1.556-0.231 0.262-0.462 0.3-0.856 0.1s-1.675-0.619-3.188-1.969c-1.175-1.050-1.975-2.35-2.206-2.744s-0.025-0.613 0.175-0.806c0.181-0.175 0.394-0.463 0.594-0.694s0.262-0.394 0.394-0.662c0.131-0.262 0.069-0.494-0.031-0.694s-0.894-2.15-1.219-2.944c-0.319-0.775-0.65-0.669-0.894-0.681-0.231-0.012-0.494-0.012-0.756-0.012s-0.694 0.1-1.056 0.494c-0.363 0.394-1.387 1.356-1.387 3.306s1.419 3.831 1.619 4.1c0.2 0.262 2.794 4.269 6.769 5.981 0.944 0.406 1.681 0.65 2.256 0.837 0.95 0.3 1.813 0.256 2.494 0.156 0.762-0.113 2.344-0.956 2.675-1.881s0.331-1.719 0.231-1.881c-0.094-0.175-0.356-0.275-0.756-0.475z"></path>
			</svg>
		</a>
	</div>
	<?php
	return ob_get_clean();
}

get_footer();