<?php
require_once 'includes/db.php';
require_once 'includes/functions.php';

$kok_dizin = "/magaza/";

// 1. URL'den gelen slug'ı kontrol et
if (!isset($_GET['slug']) || empty($_GET['slug'])) {
    header("Location: " . $kok_dizin . "blog.php");
    exit;
}
$slug = trim($_GET['slug']);

// 2. Yazı Bilgilerini Çek
$stmt = $db->prepare("
    SELECT b.*, c.name as cat_name, c.slug as cat_slug 
    FROM blogs b
    LEFT JOIN blog_categories c ON b.category_id = c.id
    WHERE b.slug = ? AND b.status = 1
");
$stmt->execute([$slug]);
$yazi = $stmt->fetch();

// Yazı yoksa ana blog sayfasına at
if (!$yazi) {
    header("Location: " . $kok_dizin . "blog.php");
    exit;
}

// 3. Görüntülenme Sayısını Artır (Aynı ziyarette spam artışı engellemek için Session kullanılabilir ama basitçe UPDATE yapıyoruz)
if(!isset($_SESSION['yazi_okundu_'.$yazi['id']])) {
    $db->query("UPDATE blogs SET view_count = view_count + 1 WHERE id = " . $yazi['id']);
    $_SESSION['yazi_okundu_'.$yazi['id']] = true;
    $yazi['view_count'] += 1;
}

$ana_gorsel = !empty($yazi['image']) ? $yazi['image'] : 'assets/img/no-image.jpg';

// Sağ menü için Son 5 Yazı
$son_yazilar = $db->prepare("SELECT title, slug, image, created_at FROM blogs WHERE id != ? AND status = 1 ORDER BY id DESC LIMIT 5");
$son_yazilar->execute([$yazi['id']]);
$son_yazilar = $son_yazilar->fetchAll(PDO::FETCH_ASSOC);

// Sağ menü için Kategoriler
$kategoriler = $db->query("SELECT * FROM blog_categories WHERE status = 1 ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

// SEO ve Meta Tag Değişkenleri
$page_title = !empty($yazi['meta_title']) ? $yazi['meta_title'] . " | SINAVKOCU" : $yazi['title'] . " | SINAVKOCU";
$meta_desc = !empty($yazi['meta_description']) ? $yazi['meta_description'] : mb_substr(strip_tags($yazi['content']), 0, 155);

// Google Article Schema Kodu
$schema_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$schema = [
    "@context" => "https://schema.org",
    "@type" => "Article",
    "headline" => $yazi['title'],
    "image" => [
      "https://" . $_SERVER['HTTP_HOST'] . $kok_dizin . $ana_gorsel
     ],
    "datePublished" => date('Y-m-d\TH:i:sP', strtotime($yazi['created_at'])),
    "author" => [
        "@type" => "Organization",
        "name" => "Sınav Koçu"
    ],
    "publisher" => [
        "@type" => "Organization",
        "name" => "Sınav Koçu",
        "logo" => [
            "@type" => "ImageObject",
            "url" => "https://" . $_SERVER['HTTP_HOST'] . $kok_dizin . "assets/img/logo.png"
        ]
    ],
    "description" => $meta_desc
];

require_once 'header.php';
?>

<meta property="og:title" content="<?= htmlspecialchars($page_title) ?>" />
<meta property="og:description" content="<?= htmlspecialchars($meta_desc) ?>" />
<meta property="og:image" content="https://<?= $_SERVER['HTTP_HOST'] ?><?= $kok_dizin ?><?= $ana_gorsel ?>" />
<meta property="og:url" content="<?= $schema_url ?>" />
<meta name="twitter:card" content="summary_large_image" />

<script type="application/ld+json"><?= json_encode($schema, JSON_UNESCAPED_UNICODE); ?></script>

<main class="container py-4 text-dark">
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb mb-0">
            <li class="breadcrumb-item"><a href="<?= $kok_dizin ?>index.php" class="text-decoration-none"><i class="bi bi-house-door"></i> Ana Sayfa</a></li>
            <li class="breadcrumb-item"><a href="<?= $kok_dizin ?>blog.php" class="text-decoration-none">Blog</a></li>
            <?php if($yazi['cat_name']): ?>
                <li class="breadcrumb-item"><a href="<?= $kok_dizin ?>blog/kategori/<?= $yazi['cat_slug'] ?>" class="text-decoration-none"><?= htmlspecialchars($yazi['cat_name']) ?></a></li>
            <?php endif; ?>
            <li class="breadcrumb-item active text-truncate" aria-current="page" style="max-width: 400px;"><?= htmlspecialchars($yazi['title']) ?></li>
        </ol>
    </nav>

    <div class="row">
        <div class="col-lg-8 mb-5">
            <article class="bg-white rounded-4 shadow-sm border p-4 p-md-5">
                
                <?php if($yazi['cat_name']): ?>
                    <a href="<?= $kok_dizin ?>blog/kategori/<?= $yazi['cat_slug'] ?>" class="badge bg-primary mb-3 text-decoration-none p-2 fs-6">
                        <?= htmlspecialchars($yazi['cat_name']) ?>
                    </a>
                <?php endif; ?>

                <h1 class="fw-bold mb-3" style="line-height: 1.3; font-size: 2.2rem;"><?= htmlspecialchars($yazi['title']) ?></h1>
                
                <div class="d-flex align-items-center text-muted mb-4 border-bottom pb-3">
                    <div class="me-4"><i class="bi bi-calendar3 text-primary me-2"></i><?= date('d.m.Y', strtotime($yazi['created_at'])) ?></div>
                    <div class="me-4"><i class="bi bi-eye-fill text-primary me-2"></i><?= $yazi['view_count'] ?> Okunma</div>
                    <div><i class="bi bi-person-circle text-primary me-2"></i>Sınav Koçu Editör</div>
                </div>

                <img src="<?= $kok_dizin ?><?= htmlspecialchars($ana_gorsel) ?>" alt="<?= htmlspecialchars($yazi['title']) ?>" class="img-fluid rounded-4 w-100 mb-5 shadow-sm" style="max-height: 450px; object-fit: cover;">
                
                <div class="blog-content lh-lg fs-5" style="color: #444;">
                    <?= $yazi['content'] ?>
                </div>

                <div class="mt-5 pt-4 border-top bg-light p-4 rounded-4 text-center">
                    <span class="text-muted fw-bold mb-3 d-block fs-5">Bu Yazıyı Arkadaşlarınla Paylaş</span>
                    <div class="d-flex gap-3 justify-content-center">
                        <button type="button" class="btn btn-white border rounded-circle shadow-sm share-btn d-flex align-items-center justify-content-center" data-platform="whatsapp" data-url="<?= $schema_url ?>" style="width:50px; height:50px; color:#25D366; transition: 0.3s;" onmouseover="this.style.backgroundColor='#25D366'; this.style.color='#fff'" onmouseout="this.style.backgroundColor=''; this.style.color='#25D366'">
                            <i class="bi bi-whatsapp fs-4"></i>
                        </button>
                        <button type="button" class="btn btn-white border rounded-circle shadow-sm share-btn d-flex align-items-center justify-content-center" data-platform="facebook" data-url="<?= $schema_url ?>" style="width:50px; height:50px; color:#1877F2; transition: 0.3s;" onmouseover="this.style.backgroundColor='#1877F2'; this.style.color='#fff'" onmouseout="this.style.backgroundColor=''; this.style.color='#1877F2'">
                            <i class="bi bi-facebook fs-4"></i>
                        </button>
                        <button type="button" class="btn btn-white border rounded-circle shadow-sm share-btn d-flex align-items-center justify-content-center" data-platform="twitter" data-url="<?= $schema_url ?>" style="width:50px; height:50px; color:#000000; transition: 0.3s;" onmouseover="this.style.backgroundColor='#000'; this.style.color='#fff'" onmouseout="this.style.backgroundColor=''; this.style.color='#000'">
                            <i class="bi bi-twitter fs-4"></i>
                        </button>
                        <button type="button" class="btn btn-white border rounded-circle shadow-sm share-btn d-flex align-items-center justify-content-center" data-platform="copy" data-url="<?= $schema_url ?>" style="width:50px; height:50px; color:#6c757d; transition: 0.3s;" onmouseover="this.style.backgroundColor='#6c757d'; this.style.color='#fff'" onmouseout="this.style.backgroundColor=''; this.style.color='#6c757d'" title="Bağlantıyı Kopyala">
                            <i class="bi bi-link-45deg fs-3"></i>
                        </button>
                    </div>
                </div>

            </article>
        </div>

        <aside class="col-lg-4">
            
            <div class="card shadow-sm border-0 rounded-4 mb-4">
                <div class="card-header bg-white border-bottom fw-bold py-3">
                    <i class="bi bi-clock-history text-primary me-2"></i> Son Eklenen Yazılar
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush rounded-bottom-4">
                        <?php foreach($son_yazilar as $sy): 
                            $sy_gorsel = !empty($sy['image']) ? $sy['image'] : 'assets/img/no-image.jpg';
                        ?>
                            <a href="<?= $kok_dizin ?>blog/<?= $sy['slug'] ?>" class="list-group-item list-group-item-action d-flex p-3 align-items-center">
                                <img src="<?= $kok_dizin ?><?= htmlspecialchars($sy_gorsel) ?>" class="rounded object-fit-cover me-3" style="width: 70px; height: 70px;">
                                <div>
                                    <h6 class="mb-1 text-dark fw-bold" style="font-size: 0.9rem;"><?= htmlspecialchars($sy['title']) ?></h6>
                                    <small class="text-muted"><i class="bi bi-calendar me-1"></i><?= date('d.m.Y', strtotime($sy['created_at'])) ?></small>
                                </div>
                            </a>
                        <?php endforeach; ?>
                        <?php if(count($son_yazilar) == 0): ?>
                            <div class="p-3 text-muted small text-center">Başka yazı bulunmuyor.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm border-0 rounded-4 mb-4">
                <div class="card-header bg-white border-bottom fw-bold py-3">
                    <i class="bi bi-tags text-primary me-2"></i> Kategoriler
                </div>
                <div class="list-group list-group-flush rounded-bottom-4">
                    <?php foreach($kategoriler as $kat): 
                        $kat_say_stmt = $db->prepare("SELECT COUNT(*) FROM blogs WHERE category_id = ? AND status = 1");
                        $kat_say_stmt->execute([$kat['id']]);
                        $kat_sayi = $kat_say_stmt->fetchColumn();
                        
                        // Bu yazıya ait kategoriyse vurgula
                        $is_active = ($yazi['category_id'] == $kat['id']) ? 'bg-primary bg-opacity-10 text-primary fw-bold' : '';
                    ?>
                        <a href="<?= $kok_dizin ?>blog/kategori/<?= $kat['slug'] ?>" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center <?= $is_active ?>">
                            <?= htmlspecialchars($kat['name']) ?>
                            <span class="badge bg-light text-dark rounded-pill border"><?= $kat_sayi ?></span>
                        </a>
                    <?php endforeach; ?>
                </div>
                
                
                
            </div>
            
            <div class="card bg-primary text-white shadow-sm border-0 rounded-4 text-center p-4">
                <i class="bi bi-rocket-takeoff fs-1 mb-2"></i>
                <h5 class="fw-bold">Sınavlara Hazır Mısın?</h5>
                <p class="small text-white-50">Özel deneme paketlerimizle başarıyı yakala.</p>
                <a href="<?= $kok_dizin ?>deneme-paketi-olustur.php" class="btn btn-light btn-sm fw-bold rounded-pill text-primary">Paketini Oluştur</a>
            </div>

        </aside>
    </div>
</main>

<style>
/* Blog İçerik Tipografisi */
.blog-content p { margin-bottom: 1.5rem; }
.blog-content img { max-width: 100%; height: auto; border-radius: 8px; margin: 15px 0; }
.blog-content h2, .blog-content h3, .blog-content h4 { font-weight: bold; margin-top: 1.5rem; margin-bottom: 1rem; color: #2c3e50; }
.blog-content ul, .blog-content ol { margin-bottom: 1.5rem; padding-left: 2rem; }
.blog-content blockquote { border-left: 4px solid #0d6efd; padding-left: 1rem; color: #6c757d; font-style: italic; background: #f8f9fa; padding: 15px; border-radius: 0 8px 8px 0; }
</style>

<script>
// Paylaşım Butonları JS Mantığı (Ürün detaydaki ile aynıdır)
document.querySelectorAll('.share-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        let platform = this.getAttribute('data-platform');
        let url = this.getAttribute('data-url');
        let text = encodeURIComponent("Şu harika yazıya göz atmalısın: ");
        let shareUrl = '';

        if (platform === 'whatsapp') shareUrl = 'https://api.whatsapp.com/send?text=' + text + encodeURIComponent(url);
        if (platform === 'facebook') shareUrl = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url);
        if (platform === 'twitter') shareUrl = 'https://twitter.com/intent/tweet?text=' + text + '&url=' + encodeURIComponent(url);

        if(platform === 'copy') {
            navigator.clipboard.writeText(url).then(() => {
                if(typeof Swal !== 'undefined') {
                    Swal.fire({ icon: 'success', title: 'Kopyalandı!', text: 'Bağlantı panoya kopyalandı.', timer: 1500, showConfirmButton: false });
                } else {
                    alert("Bağlantı kopyalandı!");
                }
            });
        } else {
            window.open(shareUrl, '_blank', 'width=600,height=500,toolbar=0,status=0');
        }
    });
});
</script>

<?php require_once 'footer.php'; ?>