<?php
require_once __DIR__ . '/config.php';

$pageTitle       = "Karot Rehberi & Saha Notları | " . SITE_NAME;
$metaDescription = "Karot delme, beton kesme, klima karotu, karot fiyatları ve karotçu seçimi konularında saha pratiğine dayalı rehber yazıları. " . PHONE_FORMATTED;
$currentPage     = "blog";
$canonicalUrl    = canonicalUrl('/blog');
$ogImage         = defaultOgImage();

// Tüm blog yazılarını oku
$posts = [];
$blogDir = __DIR__ . '/data/blog';
if (is_dir($blogDir)) {
    foreach (glob($blogDir . '/*.json') as $f) {
        $d = json_decode((string)file_get_contents($f), true);
        if (is_array($d) && !empty($d['slug'])) {
            $posts[] = $d;
        }
    }
}
// Yeniden eskiye sırala
usort($posts, function($a, $b) {
    return strcmp((string)($b['published_at'] ?? ''), (string)($a['published_at'] ?? ''));
});

// Featured post: featured=true varsa o, yoksa en yeni
$featured = null;
foreach ($posts as $p) {
    if (!empty($p['featured'])) { $featured = $p; break; }
}
if ($featured === null && !empty($posts)) $featured = $posts[0];
$rest = array_filter($posts, function($p) use ($featured) {
    return $featured === null || $p['slug'] !== $featured['slug'];
});

// Kategorileri çıkar
$categories = [];
foreach ($posts as $p) {
    $cat = $p['category'] ?? 'Rehber';
    $categories[$cat] = ($categories[$cat] ?? 0) + 1;
}
ksort($categories);

include __DIR__ . '/inc/header.php';
?>

<main>
    <div class="border-b" style="background: var(--color-concrete); border-color: var(--color-line);">
        <div class="container mx-auto px-4 py-3">
            <nav class="text-sm" aria-label="Breadcrumb">
                <a href="/" class="hover:underline" style="color: var(--color-cta);">Ana Sayfa</a>
                <span class="mx-2 text-gray-400">/</span>
                <span class="text-gray-700">Karot Rehberi</span>
            </nav>
        </div>
    </div>

    <section style="background: linear-gradient(180deg, #0f1f3a 0%, #1f2a44 100%); color:#fff;">
        <div class="container mx-auto px-4 py-14 md:py-16">
            <div class="max-w-3xl">
                <p class="text-sm font-semibold uppercase tracking-widest mb-3" style="color:#fdba74;">Karot Rehberi</p>
                <h1 class="text-3xl md:text-5xl font-extrabold mb-4">Saha Pratiğinden Karot &amp; Karotçu Notları</h1>
                <p class="text-lg text-gray-200 max-w-2xl">
                    Karot delme, klima karotu, beton kesme, karot fiyatlandırması ve karotçu seçimi üzerine sahasal rehber yazıları.
                    Her yazı saha tecrübesinden ve mühendislik standartlarından beslenir.
                </p>
                <div class="mt-6 flex flex-wrap gap-3 text-sm">
                    <span class="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-white/10 border border-white/20"><strong><?php echo count($posts); ?></strong> rehber yazısı</span>
                    <span class="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-white/10 border border-white/20"><strong><?php echo count($categories); ?></strong> kategori</span>
                </div>
            </div>
        </div>
    </section>

    <!-- Featured post -->
    <?php if ($featured): ?>
    <section class="py-10 md:py-14 bg-white">
        <div class="container mx-auto px-4">
            <p class="text-xs font-semibold uppercase tracking-widest mb-4" style="color: var(--color-cta);">⭐ Öne Çıkan Rehber</p>
            <a href="/blog/<?php echo e($featured['slug']); ?>" class="grid md:grid-cols-2 gap-6 md:gap-10 group items-center">
                <?php if (!empty($featured['image'])): ?>
                <div class="aspect-[16/10] rounded-xl overflow-hidden border" style="border-color: var(--color-line);">
                    <img src="<?php echo e($featured['image']); ?>"
                         alt="<?php echo e($featured['image_alt'] ?? $featured['title']); ?>"
                         width="<?php echo (int)($featured['image_w'] ?? 1200); ?>" height="<?php echo (int)($featured['image_h'] ?? 800); ?>"
                         loading="eager"
                         style="width:100%;height:100%;object-fit:cover;">
                </div>
                <?php endif; ?>
                <div>
                    <div class="text-xs font-semibold uppercase tracking-widest mb-3" style="color: var(--color-cta);">
                        <?php echo e($featured['category'] ?? 'Rehber'); ?>
                        <?php if (!empty($featured['reading_minutes'])): ?>
                            &middot; <?php echo (int)$featured['reading_minutes']; ?> dk okuma
                        <?php endif; ?>
                    </div>
                    <h2 class="text-2xl md:text-4xl font-extrabold mb-3 leading-tight group-hover:underline" style="color: var(--color-ink);">
                        <?php echo e($featured['title']); ?>
                    </h2>
                    <p class="text-gray-600 text-base md:text-lg mb-4 leading-relaxed"><?php echo e($featured['summary'] ?? ''); ?></p>
                    <span class="inline-flex items-center gap-1 font-semibold" style="color: var(--color-cta);">
                        Yazıyı oku &rarr;
                    </span>
                </div>
            </a>
        </div>
    </section>
    <?php endif; ?>

    <!-- Kategori filtresi + grid -->
    <section class="py-10 md:py-14" style="background: var(--color-concrete);">
        <div class="container mx-auto px-4">
            <div class="flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-8">
                <div>
                    <h2 class="text-2xl md:text-3xl font-extrabold" style="color: var(--color-ink);">Tüm Rehber Yazıları</h2>
                    <p class="text-gray-600 mt-1">Konuya göre filtreleyebilir veya tüm liste içinden seçebilirsiniz.</p>
                </div>
            </div>

            <!-- Kategori chip filtresi -->
            <div class="flex flex-wrap gap-2 mb-8" id="cat-chips" role="tablist" aria-label="Kategori filtresi">
                <button type="button" data-cat="all" class="cat-chip active px-4 py-2 rounded-full text-sm font-semibold border transition" style="border-color: var(--color-cta); background: var(--color-cta); color:#fff;">
                    Tümü (<?php echo count($posts); ?>)
                </button>
                <?php foreach ($categories as $cat => $c): ?>
                <button type="button" data-cat="<?php echo e($cat); ?>" class="cat-chip px-4 py-2 rounded-full text-sm font-semibold border bg-white transition" style="border-color: var(--color-line); color: var(--color-ink);">
                    <?php echo e($cat); ?> (<?php echo (int)$c; ?>)
                </button>
                <?php endforeach; ?>
            </div>

            <?php if (empty($posts)): ?>
                <p class="text-gray-600">Henüz yayınlanmış yazı bulunmuyor.</p>
            <?php else: ?>
            <div id="posts-grid" class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php foreach ($posts as $p):
                    $w = (int)($p['image_w'] ?? 1200);
                    $h = (int)($p['image_h'] ?? 800);
                    $cat = $p['category'] ?? 'Rehber';
                ?>
                <article class="post-card border rounded-lg overflow-hidden flex flex-col bg-white hover:border-orange-500 hover:shadow transition" data-cat="<?php echo e($cat); ?>" style="border-color: var(--color-line);">
                    <a href="/blog/<?php echo e($p['slug']); ?>" class="block aspect-[16/10] overflow-hidden bg-gray-100">
                        <?php if (!empty($p['image'])): ?>
                        <img src="<?php echo e($p['image']); ?>"
                             alt="<?php echo e($p['image_alt'] ?? $p['title']); ?>"
                             width="<?php echo e($w); ?>" height="<?php echo e($h); ?>"
                             loading="lazy" decoding="async"
                             style="width:100%;height:100%;object-fit:cover;display:block;">
                        <?php endif; ?>
                    </a>
                    <div class="p-6 flex-1 flex flex-col">
                        <div class="text-xs font-semibold uppercase tracking-widest mb-2" style="color: var(--color-cta);">
                            <?php echo e($cat); ?>
                            <?php if (!empty($p['reading_minutes'])): ?>
                                &middot; <?php echo (int)$p['reading_minutes']; ?> dk
                            <?php endif; ?>
                        </div>
                        <h2 class="text-lg font-bold mb-2 leading-snug" style="color: var(--color-ink);">
                            <a href="/blog/<?php echo e($p['slug']); ?>" class="hover:underline"><?php echo e($p['title']); ?></a>
                        </h2>
                        <p class="text-gray-600 text-sm mb-4 flex-1"><?php echo e($p['summary'] ?? ''); ?></p>
                        <div class="flex items-center justify-between text-xs text-gray-500">
                            <time datetime="<?php echo e($p['published_at']); ?>"><?php echo e(date('d.m.Y', strtotime((string)$p['published_at']))); ?></time>
                            <a href="/blog/<?php echo e($p['slug']); ?>" class="font-semibold" style="color: var(--color-cta);">Oku &rarr;</a>
                        </div>
                    </div>
                </article>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </section>

    <section class="py-12" style="background: var(--color-cta); color:#fff;">
        <div class="container mx-auto px-4 text-center">
            <h2 class="text-2xl md:text-3xl font-extrabold mb-3">Projenize Özel Bilgi mi Lazım?</h2>
            <p class="text-lg mb-6 opacity-95 max-w-2xl mx-auto">Saha pratiğinden konuşalım; kısa görüşmeyle keşif planlayalım.</p>
            <div class="flex flex-col sm:flex-row gap-3 justify-center">
                <a href="tel:<?php echo e(PHONE_TEL); ?>" class="bg-white font-bold py-3 px-6 rounded-md" style="color: var(--color-ink);">
                    Ara: <?php echo e(PHONE_FORMATTED); ?>
                </a>
                <a href="/iletisim" class="bg-white/10 hover:bg-white/15 border border-white/30 font-semibold py-3 px-6 rounded-md">
                    İletişim Formu
                </a>
            </div>
        </div>
    </section>
</main>

<script>
(function(){
    var chips = document.querySelectorAll('.cat-chip');
    var cards = document.querySelectorAll('.post-card');
    chips.forEach(function(chip){
        chip.addEventListener('click', function(){
            chips.forEach(function(c){
                c.classList.remove('active');
                c.style.background = '#fff';
                c.style.color = 'var(--color-ink)';
                c.style.borderColor = 'var(--color-line)';
            });
            chip.classList.add('active');
            chip.style.background = 'var(--color-cta)';
            chip.style.color = '#fff';
            chip.style.borderColor = 'var(--color-cta)';

            var sel = chip.dataset.cat;
            cards.forEach(function(card){
                card.style.display = (sel === 'all' || card.dataset.cat === sel) ? '' : 'none';
            });
        });
    });
})();
</script>

<?php
$breadcrumb = [
    '@type' => 'BreadcrumbList',
    'itemListElement' => [
        [ '@type' => 'ListItem', 'position' => 1, 'name' => 'Ana Sayfa', 'item' => SITE_URL . '/' ],
        [ '@type' => 'ListItem', 'position' => 2, 'name' => 'Karot Rehberi', 'item' => $canonicalUrl ],
    ],
];

$itemList = [
    '@type' => 'ItemList',
    'itemListElement' => [],
];
$pos = 1;
foreach ($posts as $p) {
    $itemList['itemListElement'][] = [
        '@type'    => 'ListItem',
        'position' => $pos++,
        'url'      => SITE_URL . '/blog/' . $p['slug'],
        'name'     => $p['title'],
    ];
}

echo renderJsonLd([
    '@context' => 'https://schema.org',
    '@graph' => [
        $breadcrumb,
        [
            '@type' => 'Blog',
            '@id'   => $canonicalUrl,
            'url'   => $canonicalUrl,
            'name'  => $pageTitle,
            'description' => $metaDescription,
            'inLanguage'  => 'tr-TR',
            'publisher'   => [ '@id' => organizationId() ],
            'mainEntity'  => $itemList,
        ],
        [
            '@type' => 'Organization',
            '@id'   => organizationId(),
            'name'  => SITE_NAME,
            'url'   => SITE_URL,
            'logo'  => SITE_URL . '/images/favicon.svg',
        ],
    ],
]);

include __DIR__ . '/inc/footer.php';
