<?php
/**
 * gazeteler.php - aahaber.com Günün Gazete Manşetleri & TikTok Tarzı Dikey Akış
 */

// 1. Parametreler ve Tarih Formatlama
$target_date = isset($_GET['date']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['date']) ? $_GET['date'] : date('Y-m-d');
$target_slug = isset($_GET['slug']) ? trim($_GET['slug']) : (isset($_GET['gazete']) ? trim($_GET['gazete']) : '');

// Tarih sınır kontrolü: 2024-01-01 ile Bugün
if ($target_date < '2024-01-01') $target_date = '2024-01-01';
$today = date('Y-m-d');
if ($target_date > $today) $target_date = $today;

// Türkçe Tarih Yardımcısı
function format_tr_newspaper_date($date_str) {
    $ts = strtotime($date_str);
    if (!$ts) return $date_str;
    $aylar = [1 => 'Ocak', 2 => 'Şubat', 3 => 'Mart', 4 => 'Nisan', 5 => 'Mayıs', 6 => 'Haziran', 7 => 'Temmuz', 8 => 'Ağustos', 9 => 'Eylül', 10 => 'Ekim', 11 => 'Kasım', 12 => 'Aralık'];
    $gunler = ['Sunday' => 'Pazar', 'Monday' => 'Pazartesi', 'Tuesday' => 'Salı', 'Wednesday' => 'Çarşamba', 'Thursday' => 'Perşembe', 'Friday' => 'Cuma', 'Saturday' => 'Cumartesi'];
    $d = date('j', $ts);
    $m = $aylar[(int)date('n', $ts)] ?? '';
    $y = date('Y', $ts);
    $day = $gunler[date('l', $ts)] ?? '';
    return "$d $m $y $day";
}

$tr_date_full = format_tr_newspaper_date($target_date);
$tr_date_short = date('j', strtotime($target_date)) . ' ' . ([1 => 'Ocak', 2 => 'Şubat', 3 => 'Mart', 4 => 'Nisan', 5 => 'Mayıs', 6 => 'Haziran', 7 => 'Temmuz', 8 => 'Ağustos', 9 => 'Eylül', 10 => 'Ekim', 11 => 'Kasım', 12 => 'Aralık'][(int)date('n', strtotime($target_date))] ?? '') . ' ' . date('Y', strtotime($target_date));

// Bilinen Gazete İsim ve Kategori Haritası
$known_newspapers = [
    'hurriyet' => ['name' => 'Hürriyet', 'category' => 'Ulusal'],
    'hurriyet-daily-news' => ['name' => 'Hürriyet Daily News', 'category' => 'Yabancı Dilde'],
    'sabah' => ['name' => 'Sabah', 'category' => 'Ulusal'],
    'daily-sabah' => ['name' => 'Daily Sabah', 'category' => 'Yabancı Dilde'],
    'sozcu' => ['name' => 'Sözcü', 'category' => 'Ulusal'],
    'cumhuriyet' => ['name' => 'Cumhuriyet', 'category' => 'Ulusal'],
    'milliyet' => ['name' => 'Milliyet', 'category' => 'Ulusal'],
    'aksam' => ['name' => 'Akşam', 'category' => 'Ulusal'],
    'turkiye-gazetesi' => ['name' => 'Türkiye Gazetesi', 'category' => 'Ulusal'],
    'turkiye' => ['name' => 'Türkiye Gazetesi', 'category' => 'Ulusal'],
    'yeni-safak' => ['name' => 'Yeni Şafak', 'category' => 'Ulusal'],
    'karar' => ['name' => 'Karar', 'category' => 'Ulusal'],
    'birgun' => ['name' => 'BirGün', 'category' => 'Ulusal'],
    'evrensel' => ['name' => 'Evrensel', 'category' => 'Ulusal'],
    'posta' => ['name' => 'Posta', 'category' => 'Ulusal'],
    'takvim' => ['name' => 'Takvim', 'category' => 'Ulusal'],
    'aydinlik-gazetesi' => ['name' => 'Aydınlık', 'category' => 'Ulusal'],
    'aydinlik' => ['name' => 'Aydınlık', 'category' => 'Ulusal'],
    'milli-gazete' => ['name' => 'Milli Gazete', 'category' => 'Ulusal'],
    'yeni-akit' => ['name' => 'Yeni Akit', 'category' => 'Ulusal'],
    'turkgun' => ['name' => 'Türkgün', 'category' => 'Ulusal'],
    'nefes' => ['name' => 'Nefes', 'category' => 'Ulusal'],
    'dirilis-postasi' => ['name' => 'Diriliş Postası', 'category' => 'Ulusal'],
    'yeni-asya' => ['name' => 'Yeni Asya', 'category' => 'Ulusal'],
    'yenicag' => ['name' => 'Yeniçağ', 'category' => 'Ulusal'],
    'yenibirlik' => ['name' => 'YeniBirlik', 'category' => 'Ulusal'],
    'milat' => ['name' => 'Milat', 'category' => 'Ulusal'],
    'korkusuz' => ['name' => 'Korkusuz', 'category' => 'Ulusal'],
    'tavir-gazetesi' => ['name' => 'Tavır', 'category' => 'Ulusal'],
    'kibris' => ['name' => 'Kıbrıs Gazetesi', 'category' => 'Kıbrıs'],
    'fanatik' => ['name' => 'Fanatik', 'category' => 'Spor'],
    'fotomac' => ['name' => 'Fotomaç', 'category' => 'Spor'],
    'dunya' => ['name' => 'Dünya', 'category' => 'Ekonomi']
];

// İstenen Gazetenin Tespiti (Önbellek Dosyasından veya Sözlükten)
$selected_gazete = null;
$clean_slug_key = str_replace(['-gazetesi-manseti', '-manseti', '-gazetesi'], '', $target_slug);

// 1. data/gazete_cache/{date}.json veya data/gazeteler.json içinden ara
$items_pool = [];
$cache_file = __DIR__ . '/data/gazete_cache/' . $target_date . '.json';
if (file_exists($cache_file)) {
    $c_data = json_decode(@file_get_contents($cache_file), true);
    if (!empty($c_data['items'])) {
        $items_pool = $c_data['items'];
    }
}
if (empty($items_pool) || count($items_pool) < 20) {
    $def_file = __DIR__ . '/data/gazeteler.json';
    if (file_exists($def_file)) {
        $d_data = json_decode(@file_get_contents($def_file), true);
        if (!empty($d_data['items']) && count($d_data['items']) > count($items_pool)) {
            $items_pool = $d_data['items'];
        }
    }
}
if (!empty($items_pool)) {
    foreach ($items_pool as $it) {
        if ($it['slug'] === $target_slug || $it['key'] === $clean_slug_key || strpos($it['slug'], $clean_slug_key) !== false) {
            $selected_gazete = $it;
            break;
        }
    }
}

// Bulunamadıysa bilinenler sözlüğünden oluştur
if (!$selected_gazete && isset($known_newspapers[$clean_slug_key])) {
    $kn = $known_newspapers[$clean_slug_key];
    $selected_gazete = [
        'title' => $kn['name'],
        'slug' => $target_slug,
        'key' => $clean_slug_key,
        'category' => strtolower($kn['category'])
    ];
}

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'] ?? 'aahaber.com';
$request_uri = $_SERVER['REQUEST_URI'] ?? '/';
$base_path = (strpos($request_uri, '/aahaber/') === 0 || strpos($_SERVER['SCRIPT_NAME'] ?? '', '/aahaber/') === 0) ? '/aahaber/' : '/';

if (!empty($target_slug) && $selected_gazete) {
    $g_title = $selected_gazete['title'];
    $g_image = $selected_gazete['full'] ?? ($selected_gazete['thumb_2x'] ?? ($selected_gazete['thumb'] ?? ''));

    // Gazeteye Özel SEO & Meta Bilgileri
    $page_title = "{$tr_date_short} {$g_title} Gazetesi 1. Sayfa Manşeti — aahaber.com";
    $page_desc = "{$tr_date_short} tarihli {$g_title} Gazetesi birinci sayfa manşetini HD kalitede okuyun. Günün {$g_title} gazete manşetleri, ilk sayfa haberleri ve detayları aahaber'de.";
    
    $clean_g_lower = mb_strtolower($g_title, 'UTF-8');
    $page_keywords = "{$clean_g_lower} gazetesi, {$clean_g_lower} manşeti, {$clean_g_lower} oku, {$clean_g_lower} bugünkü manşeti, {$tr_date_short} {$clean_g_lower}, {$clean_g_lower} 1. sayfa, gazete manşetleri, günün gazete manşetleri, hd manşet oku, aahaber";
    
    $canonical_url = "{$protocol}{$host}{$base_path}gazeteler/{$target_date}/{$target_slug}";
    $og_image = $g_image;

    // Schema.org Structured Data
    $schema_json = [
        "@context" => "https://schema.org",
        "@type" => "NewsArticle",
        "headline" => "{$tr_date_short} {$g_title} Gazetesi 1. Sayfa Manşeti",
        "description" => $page_desc,
        "datePublished" => $target_date . "T06:00:00+03:00",
        "dateModified" => $target_date . "T06:00:00+03:00",
        "mainEntityOfPage" => [
            "@type" => "WebPage",
            "@id" => $canonical_url
        ],
        "author" => [
            "@type" => "Organization",
            "name" => $g_title
        ],
        "publisher" => [
            "@type" => "Organization",
            "name" => "aahaber",
            "logo" => [
                "@type" => "ImageObject",
                "url" => "{$protocol}{$host}{$base_path}favicon.ico"
            ]
        ]
    ];
    if (!empty($g_image)) {
        $schema_json["image"] = [$g_image];
    }
} else {
    // Genel Gazeteler Sayfası
    $page_title = "{$tr_date_short} Günün Gazete Manşetleri — aahaber.com Tüm Gazeteler 1. Sayfalar";
    $page_desc = "{$tr_date_short} günün gazete manşetleri. Türkiye'nin tüm ulusal, spor, ekonomi ve Kıbrıs gazetelerinin bugünkü 1. sayfa manşetlerini HD kalitede tek ekranda okuyun.";
    $page_keywords = "gazete manşetleri, bugünkü gazeteler, {$tr_date_short} gazete manşetleri, günün manşetleri, ulusal gazeteler, spor manşetleri, gazete oku, birinci sayfalar, aahaber";
    $canonical_url = "{$protocol}{$host}{$base_path}gazeteler" . ($target_date !== $today ? "/{$target_date}" : "");
}

$page_active = "gazeteler";
$search_placeholder = "Gazete ara (örn: Hürriyet, Sabah, Sözcü, Fanatik)...";

require_once __DIR__ . '/ust.php';
?>

<!-- Ana Gazeteler Konteyneri -->
<div class="gazete-page-container" id="gazetePageContainer">

  <!-- =========================================================================
       GÖRÜNÜM 1: TÜM GAZETELER GALERİ / GRID GÖRÜNÜMÜ (Resim 1)
       ========================================================================= -->
  <div class="gazete-grid-view" id="gazeteGridView">

    <!-- 1. ÜST BİLGİ VE BAŞLIK ŞERİDİ -->
    <div class="gazete-header-banner">
      <div class="gazete-header-title-box">
        <div class="gazete-breadcrumb">
          <a href="index.php">Anasayfa</a>
          <span>&rsaquo;</span>
          <strong>Gazete Manşetleri</strong>
        </div>
        <h1 class="gazete-main-heading">Günün Gazete Manşetleri</h1>
      </div>

      <div class="gazete-header-stats-pill">
        <span class="gazete-badge-live"></span>
        <span id="gazeteHeaderDateTag">Bugün</span>
        <span class="gazete-stat-sep">•</span>
        <span id="gazeteHeaderCountTag">31 Gazete Manşeti</span>
        <span class="gazete-stat-sep">•</span>
        <span class="gazete-hd-tag">HD Manşet</span>
      </div>
    </div>

    <!-- 2. KONTROL & FİLTRE PANELİ -->
    <div class="gazete-controls-panel">
      
      <!-- Üst Satır: Hızlı Tarihler, Tarih Seçici ve Arama -->
      <div class="gazete-controls-top-row">
        
        <!-- Hızlı Tarih Butonları: Bugün, Dün, Önceki Gün -->
        <div class="gazete-date-btn-group">
          <button type="button" class="gazete-quick-date-btn active" data-days="0" id="btnDateToday">
            Bugün
          </button>
          <button type="button" class="gazete-quick-date-btn" data-days="1" id="btnDateYesterday">
            Dün
          </button>
          <button type="button" class="gazete-quick-date-btn" data-days="2" id="btnDatePrevDay">
            Önceki Gün
          </button>
        </div>

        <!-- Takvim Tarih Seçici (Sınır: 2024-01-01 - Bugün) -->
        <div class="gazete-datepicker-box">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3">
            <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
            <line x1="16" y1="2" x2="16" y2="6"></line>
            <line x1="8" y1="2" x2="8" y2="6"></line>
            <line x1="3" y1="10" x2="21" y2="10"></line>
          </svg>
          <input type="date" id="gazeteDateInput" min="2024-01-01" max="<?= date('Y-m-d') ?>" value="<?= htmlspecialchars($target_date) ?>" title="Tarih Değiştir">
        </div>

        <!-- Gazete Arama Kutusu -->
        <div class="gazete-search-wrap">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3">
            <circle cx="11" cy="11" r="8"></circle>
            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
          </svg>
          <input type="text" id="gazeteSearchInput" placeholder="Gazete ara (örn: Hürriyet, Sabah, Sözcü, Kıbrıs)..." autocomplete="off">
          <button type="button" id="gazeteSearchClear" class="gazete-search-clear-btn" style="display: none;">&times;</button>
        </div>

      </div>

      <!-- Alt Satır: Kategori Filtre Sekmeleri -->
      <div class="gazete-categories-bar" id="gazeteCategoriesBar">
        <button type="button" class="gazete-cat-tab active" data-cat="all">
          <span>Tümü</span>
          <span class="gazete-cat-count" id="countAll">31</span>
        </button>
        <button type="button" class="gazete-cat-tab" data-cat="ulusal">
          <span>Ulusal</span>
          <span class="gazete-cat-count" id="countUlusal">25</span>
        </button>
        <button type="button" class="gazete-cat-tab" data-cat="spor">
          <span>⚽ Spor</span>
          <span class="gazete-cat-count" id="countSpor">2</span>
        </button>
        <button type="button" class="gazete-cat-tab" data-cat="ekonomi">
          <span>📈 Ekonomi</span>
          <span class="gazete-cat-count" id="countEkonomi">1</span>
        </button>
        <button type="button" class="gazete-cat-tab" data-cat="yabanci">
          <span>🌍 Yabancı Dilde</span>
          <span class="gazete-cat-count" id="countYabanci">2</span>
        </button>
        <button type="button" class="gazete-cat-tab" data-cat="kibris" id="tabKibris">
          <span>🌴 Kıbrıs</span>
          <span class="gazete-cat-count" id="countKibris">1</span>
        </button>
      </div>

    </div>

    <!-- 3. GAZETELER KART IZGARASI (GRID - Resim 1 Kaliteli Küçük Resimler) -->
    <div class="gazete-grid" id="gazeteGrid">
      <div class="gazete-loading-state">
        <div class="tv-spinner" style="margin: 0 auto 14px; width: 36px; height: 36px; border-width: 3px;"></div>
        <p style="font-size: 14px; font-weight: 600; color: var(--text-muted);">Günün gazete manşetleri yükleniyor...</p>
      </div>
    </div>

    <!-- Boş Sonuç Durumu -->
    <div class="gazete-empty-state" id="gazeteEmptyState" style="display: none;">
      <div class="gazete-empty-icon">📰</div>
      <h3 class="gazete-empty-title">Aramanıza Uygun Gazete Bulunamadı</h3>
      <p class="gazete-empty-desc">Lütfen arama teriminizi kontrol edin veya farklı bir kategori seçin.</p>
      <button type="button" class="gazete-empty-btn" id="gazeteResetFiltersBtn">Filtreleri Temizle</button>
    </div>

  </div>


  <!-- =========================================================================
       GÖRÜNÜM 2: TİKTOK TARZI DİKEY KAYDIRMALI MANŞET AKIŞI (Resim 2 & Resim 3)
       ========================================================================= -->
  <div class="gazete-feed-view" id="gazeteFeedView" style="display: none;">
    
    <!-- Sabit Üst Kontrol & Navigasyon Çubuğu (Resim 2) -->
    <div class="feed-top-navbar" id="feedTopNavbar">
      <div class="feed-nav-inner">
        
        <!-- Sol: Ekmek Kırıntısı (Breadcrumbs) & Geri Butonu -->
        <div class="feed-nav-left">
          <button type="button" class="btn-feed-back" id="btnFeedBackToGrid" title="Galeri Görünümüne Dön">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="15 18 9 12 15 6"></polyline></svg>
            <span>Tüm Gazeteler</span>
          </button>
          <div class="feed-breadcrumb-line">
            <a href="index.php">Anasayfa</a>
            <span>/</span>
            <a href="gazeteler.php" id="feedBreadcrumbAll">Gazeteler</a>
            <span>/</span>
            <span class="active" id="feedBreadcrumbTitle">Hürriyet Gazetesi</span>
          </div>
        </div>

        <!-- Sağ: Gazete Seç Dropdown + Tarih + [Getir] Butonu (Resim 2 Birebir) -->
        <div class="feed-nav-controls">
          <!-- Gazete Seçim Dropdown -->
          <div class="feed-select-wrap">
            <select id="feedNewspaperSelect" class="feed-custom-select" aria-label="Gazete Değiştir">
              <!-- JS tarafından doldurulur -->
            </select>
          </div>

          <!-- Tarih Seçici -->
          <div class="feed-date-wrap">
            <input type="date" id="feedDateInput" min="2024-01-01" max="<?= date('Y-m-d') ?>" value="<?= htmlspecialchars($target_date) ?>" class="feed-custom-date">
          </div>

          <!-- [Getir] Butonu (Resim 2 Mavi Buton) -->
          <button type="button" class="btn-feed-getir" id="btnFeedGetir">
            Getir
          </button>
        </div>

      </div>
    </div>

    <!-- TikTok Tarzı Dikey Kaydırmalı Gazeteler Akış Listesi -->
    <div class="feed-stream-container" id="feedStreamContainer">
      <!-- JS tarafından her gazete için büyük manşet + başlık/bilgi + sosyal butonlar render edilir -->
    </div>

  </div>

  <!-- Alt Telif Notu -->
  <div class="gazete-footer-notice">
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <circle cx="12" cy="12" r="10"></circle>
      <line x1="12" y1="16" x2="12" y2="12"></line>
      <line x1="12" y1="8" x2="12.01" y2="8"></line>
    </svg>
    <span>Gazete manşetleri ve 1. sayfaları basın bilgilendirme amacıyla yayınlanmaktadır. Tüm hakları ilgili gazete yayıncılarına aittir.</span>
  </div>

</div>


<!-- =========================================================================
     GÖRÜNÜM 3: POPUP ZOOM LIGHTBOX (Resim 4)
     Sadece tıklandığında açılır, gezinme oku içermez, tam ekran zoom/pan yapılır.
     ========================================================================= -->
<div class="gazete-zoom-modal" id="gazeteZoomModal" style="display: none;" aria-hidden="true" role="dialog">
  <div class="gazete-zoom-backdrop" id="gazeteZoomBackdrop"></div>

  <div class="gazete-zoom-wrapper">
    <!-- Zoom Üst Araç Çubuğu -->
    <div class="gazete-zoom-toolbar">
      <div class="gazete-zoom-title-box">
        <h3 id="zoomModalTitle">Gazete Adı</h3>
        <span id="zoomModalDate">Tarih</span>
      </div>

      <div class="gazete-zoom-buttons">
        <button type="button" class="zoom-tool-btn" id="btnZoomOut" title="Uzaklaştır (-)">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line><line x1="8" y1="11" x2="14" y2="11"></line></svg>
        </button>
        <span class="zoom-factor-label" id="zoomFactorLabel">100%</span>
        <button type="button" class="zoom-tool-btn" id="btnZoomIn" title="Yakınlaştır (+)">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line><line x1="11" y1="8" x2="11" y2="14"></line><line x1="8" y1="11" x2="14" y2="11"></line></svg>
        </button>
        <button type="button" class="zoom-tool-btn" id="btnZoomReset" title="Sıfırla (1:1)">
          1:1
        </button>

        <div class="zoom-tool-sep"></div>

        <a href="#" id="btnZoomDownload" class="zoom-tool-btn download" download title="Orijinal HD Görseli İndir" target="_blank">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
          <span>İndir</span>
        </a>

        <div class="zoom-tool-sep"></div>

        <button type="button" class="zoom-tool-btn close" id="btnZoomClose" title="Kapat (ESC)">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
        </button>
      </div>
    </div>

    <!-- Zoom Görsel Sahnesi -->
    <div class="gazete-zoom-stage" id="gazeteZoomStage">
      <div class="zoom-spinner" id="zoomSpinner">
        <div class="tv-spinner" style="width: 44px; height: 44px; border-width: 3.5px;"></div>
      </div>
      <img id="zoomModalImg" class="gazete-zoom-img" src="" alt="Gazete Manşeti" draggable="false">
    </div>

    <!-- Zoom Alt İpucu -->
    <div class="gazete-zoom-bottom-hint">
      <span>💡 Fare tekerleğini çevirerek yakınlaştırabilir, basılı tutup sürükleyerek manşeti detaylı inceleyebilirsiniz.</span>
    </div>
  </div>
</div>

<script>
  window.INITIAL_TARGET_DATE = <?= json_encode($target_date) ?>;
  window.INITIAL_TARGET_SLUG = <?= json_encode($target_slug) ?>;
</script>

<?php
$extra_js = ['gazeteler.js?v=' . time()];
require_once __DIR__ . '/alt.php';
?>
